Concepts that must be known about the essence of a set-linked list

Source: Internet
Author: User
Tags define null

Concepts that must be known about the essence of a set-linked list

If you want to have an essential understanding of collections (series), linked lists are a concept that must be understood. This article mainly includes:

● Origins and definitions of linked lists
● Create a one-way linked list
● Other linked lists

 

Source and definition of linked list

In real life, we put different items in a shopping cart. In the object-oriented world, sometimes different types of data need to be put together to form a set. The elements in the set are not isolated from each other. in C #, how do we express the relationship between the elements in the set?

 

With the help of the "self-reference class", you can establish the relationship between the elements of the set. For example, there is a self-reference class:

public class Node
{
    public int Data{get;set;}
    public Node Next{get;set;}
    public Node(int dataValue)
    {}
}

The biggest feature of the Node class is that there is a Node type attribute, which points to another Node instance. The Next attribute is also called "reference chain ". In a set scenario, multiple Node instances are put into one set. Each Node instance contains a Next attribute pointing to the Next Node instance. The last Node instance in the set points to null. Shown in the figure below:

 

A linked list is a linear set of self-referenced objects, that is, a sequence.

Since each self-referenced object is linked by a reference chain, it is called a linked list. The stack and queue are linked lists of constrained versions, while the binary lookup number is a non-linear data structure.

 

Although the nodes or elements of the linked list are logically continuous and linear, when the memory is not continuously stored, the array elements are continuous in the memory, so we can access array elements through indexes.

 

Create a one-way linked list

First, create a node, which is a self-reference class:

namespace LinkedListLibrary
{
    public class ListNode
    {
// Current Node object
        public object Data { get; private set; }
// The Next attribute is also called a chain and points to another ListNode object instance. In this way, the two ListNode object instances are linked.
        public ListNode Next { get; set; }
        public ListNode(object dataValue): this(dataValue, null)
        {
            
        }
        public ListNode(object dataValue, ListNode nextNode)
        {
            Data = dataValue;
            Next = nextNode;
        }
    }
}

 

Simulate another linked list, as shown below:

namespace LinkedListLibrary
{
    public class List
    {
        private ListNode firstNode;
        private ListNode lastNode;
        private string name;
        public List(string listName)
        {
            name = listName;
            firstNode = lastNode = null;
        }
        public List() : this("list"){}
     
         ......
// If the first node is null, the set is null.
        public bool IsEmpty()
        {
            return firstNode == null;
        }
    }
}

If the first node is null, the linked list is empty. The List class provides the IsEmpty method to determine whether the linked List is empty. List also contains five other important methods.

 

Insert it before the first node of the linked list.

// Insert elements and nodes at the beginning
        public void InsertAtFront(object insertItem)
        {
If (IsEmpty () // if the set is empty, add an element, which is equivalent to the same as the first node and the second node.
            {
                firstNode = lastNode = new ListNode(insertItem);
            }
Else // If the set is not empty, the first node is the newly added element, and the first node is changed to the next node.
            {
                firstNode = new ListNode(insertItem, firstNode);
            }
        }

When the set is not empty, the newly added node is actually set as the first node, and the reference chain of the new first node is directed to the original first node.

 

Insert it after the last node of the linked list.

        public void InsertAtBack(object insertItem)
        {
If (IsEmpty () // if the original set is empty, the first and last nodes are newly added nodes.
            {
                firstNode = lastNode = new ListNode(insertItem);
            }
Else // if the original set is not empty, the attribute value of the last node is the newly added node.
            {
                lastNode = lastNode.Next = new ListNode(insertItem);
            }
        }

In the preceding example, when the set is not empty, the newly added node is actually set to the last node, and the reference chain of the last node is pointed to null.

 

Remove the node at the top of the linked list.

// Remove the first element and Node
// Reset the Next attribute of the first node.
        public object RemoveFromFront()
        {
            if (IsEmpty())
                throw new EmptyListException(name);
// Retrieve the Node object from the first node
            object removeItem = firstNode.Data;
If (firstNode = lastNode) // if the set contains only one element
            {
                firstNode = lastNode = null;
            }
Else // under normal circumstances, assign the node pointed to by the Next attribute of firstNode to the first node
            {
                firstNode = firstNode.Next;
            }
            return removeItem;
        }

In essence, the node originally ranked second is set to the first node.

 

Remove the last node of the linked list.

// Remove the last element and Node
        public object RemoveFromBack()
        {
            if (IsEmpty())
            {
                throw new EmptyListException();
            }
// Obtain the Node object from the last Node
            object removeItem = lastNode.Data;
If (firstNode = lastNode) // if the current set has only one node
            {
                firstNode = lastNode = null;
            }
            else
            {
// Use the first node as the current node
                ListNode current = firstNode; 
// Change the value of the node except the last Node
                while (current.Next != lastNode)
                {
                    current = current.Next;
                }
// The last current node is the second to last node.
                lastNode = current;
Current. Next = null; // The Next attribute of the last node is null, that is, it does not point to another node.
            }
            return removeItem;
        }

Above, from the first node, It loops until the last and second nodes. current is like a pointer. Every time you point to a node, you can set the following node of the node as the current node. Finally, set the last and last nodes. Set the reference chain of Current to null so that it can be recycled by the garbage collection mechanism.

 

Print the linked list.

// Print the display
        public void Display()
        {
            if (IsEmpty())
            {
Console. WriteLine ("set" + name + "blank ");
            }
            else
            {
Console. WriteLine ("the Set name is:" + name );
// Use the first node as the current node
                ListNode current = firstNode;
                while (current != null)
                {
// Print the current node object
                    Console.Write(current.Data + " ");
// Set the next node to the current node
                    current = current.Next;
                }
                Console.WriteLine("\n");
            }
        }   

Above, from the first node, the loop continues until the last node. current is like a pointer. Every time a node is printed, the current node is set as the next node and the loop continues.


EmptyListException is used to throw an exception where the linked list is empty.

namespace LinkedListLibrary
{
    public class EmptyListException : Exception
    {
Public EmptyListException (): base ("the current set is empty "){}
Public EmptyListException (string name): base ("set" + name + "blank "){}
        public EmptyListException(string exception, Exception inner) : base(exception, inner){}
    }
}


Client call:

using LinkedListLibrary;
namespace ListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List list = new List();
            bool aBoolean = true;
            char aChar = 'a';
            int anInt = 12;
            string aStr = "hi";
            list.InsertAtFront(aBoolean);
            list.Display();
            list.InsertAtFront(aChar);
            list.Display();
            list.InsertAtBack(anInt);
            list.Display();
            list.InsertAtBack(aStr);
            list.Display();
            object removeObject;
            try
            {
                removeObject = list.RemoveFromFront();
Console. WriteLine (removeObject + "deleted ...");
                list.Display();
                removeObject = list.RemoveFromFront();
Console. WriteLine (removeObject + "deleted ...");
                list.Display();
                removeObject = list.RemoveFromBack();
Console. WriteLine (removeObject + "deleted ...");
                list.Display();
                removeObject = list.RemoveFromBack();
Console. WriteLine (removeObject + "deleted ...");
                list.Display();
            }
            catch (EmptyListException emptyListException)
            {
                Console.Error.WriteLine("\n" + emptyListException);
            }
            Console.ReadKey();
        }
    }
}

 

Other linked lists

In the preceding example, a one-way linked list is created. The first node starts to contain a reference chain. The reference chain of each node points to the next node, and the reference chain of the last node is null. A one-way linked list can only be traversed in one direction.

 

The difference between a circular one-way linked list and a one-way linked list is that the reference chain of the last node points to the first node. The circular one-way linked list can only traverse from one direction, but after traversing to the last node, it returns to the first node and starts traversing again.

 

The first node of the two-way linked list only contains the reference chain pointing to the next node, and the last node only contains the reference chain pointing to the previous node, other nodes also contain reference chains for the previous and next nodes. Two-way linked list supports forward and backward traversal.

 

The difference between a two-way linked list and a two-way linked list is that the first node points to the last node and the forward reference chain of the last node points to the first node.

 

References:

Visual C #2008 University tutorial-(Third edition)


Concept and simple implementation of linked list in C Language

Linked List

Linked List Overview
A linked list is a common and important data structure. It is a structure for dynamic storage allocation. It can open up memory units as needed. The linked list has a "header Pointer" variable, which is represented by a head and stores an address. This address points to an element. Each element in the linked list is called a "Node", and each node should contain two parts: the actual data required by the user and the address of the next node. Therefore, head points to the first element: the first element points to the second element ;......, Until the last element, this element no longer points to other elements. It is called the "end of the table". Its address is put in a "NULL" (indicating "Empty address"), and the linked list ends here.

Unidirectional linked list
In addition to the information field, each node of the one-way linked list has a pointer field to indicate its subsequent nodes. the pointer field of the last node of the one-way linked list is NULL ). The one-way linked list is uniquely determined by the header pointer. Therefore, the one-way linked list can be named by the name of the header pointer. For example, the one-way linked list named head is called the table head, the header Pointer Points to the first node of the one-way linked list.

Simple implementation:

# Define NULL 0

Typedef int DATATYPE

Typedef struct node

{DATATYPE info;

Node * next;

} LINKLIST;

Two-way linked list
Each node contains only one pointer field pointing to the next node. This linked list is called a one-way linked list. If you want to insert a new node at the current position indicated by a pointer in the one-way linked list, you must traverse the first pointer of the linked list one by one until the previous node of the node pointed by the current pointer, and modify the pointer of this node. Each node of the two-way linked list contains two pointer fields pointing to the previous node and the next node respectively. In a two-way linked list, any node can easily find the node before and after it, instead of starting from the header node in the above insert (and delete) operation.

Simple implementation:

Typedef struct node

{DATATYPE info;

Node * priv, * next;

} DINKLIST;

Cyclic linked list
The pointer field of the last node of the one-way linked list is NULL ). If the pointer is used to point to the first node of the one-way linked list, a one-way cyclic linked list is formed.

Here is a good article: myweb.yzu.edu.cn/...ao.htm
Reference: myweb.yzu.edu.cn/..ao.htm

Define linked list

Create a linked list
/* Creat a list */
# Include "stdlib. h"
# Include "stdio. h"
# Include "conio. h"
Struct list
{
Int data;
Struct list * next;
};
Typedef struct list node;
Typedef node * link;
Void main ()
{
Link ptr, head;
Int num, I;
Ptr = (link) malloc (sizeof (node ));
Ptr = head;
Printf ("please input 5 numbers ==>\ n ");
For (I = 0; I <= 4; I ++)
{
Scanf ("% d", & num );
Ptr-> data = num;
Ptr-> next = (link) malloc (sizeof (node ));
If (I = 4) ptr-> next = NULL;
Else ptr = ptr-> next;
}
Ptr = head;
While (ptr! = NULL)
{
Printf ("The value is ==>% d \ n", ptr-> data );
Ptr = ptr-> next;
}
Getch ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.