C # bidirectional linked list and custom linked list

Source: Internet
Author: User

One, two-way linked list linkedlist<t>

The Linkedlist<t> collection class does not have a similar version of a Non-generic collection. Linkedlist<t> is a doubly linked list whose elements point to the elements before and after it.
The advantage of a linked list is that if you insert an element into the middle of a listing, it is very quick to use the linked table. When inserting an element, you simply modify the next reference of the previous element and the previous reference of the next element so that they reference the inserted element. In the list<t> and ArrayList classes, insert an element, and you need to move all the elements that follow the element.
Of course, the list also has drawbacks. The elements of a list can only be accessed one after another, which takes a long time to find elements that are in or at the end of a list.
Lists can store not only elements in a list, but also information about the next element and the previous element for each element. This is
Linkedlist<t> the reason for the element containing the linkedlistnode<t> type. Using the LinkedListNode <T> class, you can get the next element and the previous element in the list.
#region list Test/**////<summary>///list Test///</summary> public class Testlinkedlist {public void testlinklist () {linkedlist<book> Booklist = new linkedlist<book> (); Book Book1 = new book {Title = "C # Advanced Programming", Book_author = new Author {Name = "yellow old evil", address = "Peach Blossom Island"}, Price = 128f}; Book Book2 = new book {Title = "I-Java", Book_author = new Author {Name = "yin", address = "White Camel Mountain"}, Price = 138f }; BOOK3 = new book {Title = "Silverlight", Book_author = new Author {Name = "Master of Lights", address = "Dali"}, Price = 123f}; Book Book4 = new book {Title = "JavaFx", Book_author = new Author {Name = "Hong Seven public", address = "Lin ' an"}, Price = 125f}; Book Book5 = new book {Title = "WPF", Book_author = new Author {Name = "Wang Chongyang", address = "Linan"}, Price = 158f}; /**////adds Book1 to the first element of the list Booklist.addfirst (BOOK1); /**////adds book2 to the first element of the list, when the original first element automatically backs up a booklist.addfirst (BOOK2); /**////Instantiate a LinkedListNode object linkedlistnode<book> node = new linkedlistnode<book> (BOOK3); /**////adds the LinkedListNode object to the last booklist.addlast of the list (node); /**////Append an element booklist.addafter (node, BOOK4) after the last element; /**////Inserts an element booklist.addbefore (node, BOOK5) before the LinkedListNode object; foreach (var item in Booklist) {Console.WriteLine (item. Title); /**////Order Display///Console.WriteLine ("/n/n The elements in the list in sequence"); linkedlistnode<book> firstnode = Booklist.first; while (Firstnode!= null) {Console.WriteLine (firstNode.Value.Title); firstnode = Firstnode.next;}/**////reverse order display CONSOLE.W Riteline ("/n/n the elements in the list in reverse order"); linkedlistnode<book> lastnode = booklist.last; while (lastnode!= null) {Console.WriteLine (lastNode.Value.Title); lastnode = lastnode.previous;} Console.WriteLine ("The result of/n/n order"); var orderlist = Booklist.orderby (Book => Book. Price); foreach (var item in orderlist) {Console.WriteLine (string. Format ("book name {0}, price {1}", item. Title, item. Price)); }}} #endregion

second, custom linked list

public class Node<t> {public T data, public node () {} public node (t data) {This.data = data.} Public NODE&LT;T&G T next = null; The public class Link<t> {//Defines the header node of the list private node<t> head;//list Initialization public link () {head = null;}///<summa Ry>///The length of the linked list, traversing the entire linked list until the end of the list///</summary>///<returns> list length </returns> public int Count () {//Define a section Point node<t> p = head; int count = 0;//List counter//Traverse list while (P!= null) {count++ p = p.next;//move to next node} return count; }///<summary>///value///</summary>///<param name= "I" > section I node </param>///<returns& gt; The value of the I node </returns> public T getelem (int i) {//define a node node<t> p = head; int k = 0;//counter//If I is greater than the length of the list or I is less than 0, then the report Out exception if (I >= Count () | | I < 0) {throw new Exception ("Error");}//If I is greater than 0 and is less than the linked list length, then loop through the list until the first node (K < i) {k ++; p = p.next; return p.data; ///<summary>///Inserts a new node in the first position of the list///</summary>///<param name= "E" > Value to insert node;/param>///<param name= "I" > List i node </param> public void Insert (T e, int i) {node<t> p = new NODE&L T T> (e);//the node to insert node<t> q = head; int k = 0;//counter//If I is greater than the length of the list or I is less than 0, the exception is reported if (I >= Count () | | I < 0) {System.Console.WriteLine ("Error"); If inserted in the header of the list, move the head pointer if (i = = 0) {p.next = head; header = P; return;}//traverse the list until I-1 node while (K < i-1) {k++; q = q.next; ///Insert the new node in the position of the first node p.next = Q.next; Q.next = p; ///<summary>///Delete the first I node///</summary>///<param name= "I" > The first node of the list </param> public void remove at (int i) {node<t> p = head; int k = 0;//counter//If I is greater than the length of the list or I is less than 0, the exception if (I < 0 | | I >= Count ()) {system.cons Ole. WriteLine ("Error"); Return //If the header is deleted, move the head pointer if (i = = 0) {Head.next = Head.next.next return;}//traverse the list until the I-1 node while (K < i-1) {k++ p = p. Next //delete the first node P.next = P.next.next; ///<summary>///adds a new node at the end of the list///</summary>///<param name= "E" > Value of the new node </param&Gt public void Add (T e) {node<t> p = new node<t> (e);//Create a new node node<t> q = Newer node<t> ();//If the list is empty, the Assigns the new node to the head pointer if (header = = null) {heads = P; return}/*---------------------------------------* Add a new node at the end of the list if the list is not empty-------- --------------------------------///start traversing from the beginning to the end of the chain, q = head; while (Q.next!= null) {q = Q.next;}//Insert a new node at the end of the list q.next = p; ///<summary>///Find the first occurrence of an element in the list///</summary>///<param name= "E" > elements to find </param>///< Returns> the index of the first occurrence of this element in the list </returns> public int IndexOf (T e) {node<t> p = head; int k = 0;//Counter/*------- -----------------------------* Traverses the entire list until it finds the value of the first node * exits with the element equal, and returns the corresponding position of the cable * primer. If not found, returns-1. -------------------------------------///start traversal, find exit and return the corresponding location index while (p.next!= null) {if (P.data.equals (e)) { return k; } k++; p = p.next; } if (!p.data.equals (e)) {k++}//If not found, return-1 returns K >= Count ()? -1:k; ///<summary>///finds the last occurrence of an element in the list///</summary><param name= "E" > elements to look for </param>///<returns> The index of the last occurrence of this element in the list </returns> public int LastIndexOf (T e) {node<t> p = head; int index = -1;//The last occurrence of the position index int k = 0;//Counter/*-------------------------------- ----------------* Traverse the entire list until the list ends, each time the value of the corresponding node is found to be equal to the element, the index is assigned to the location of the node, * so that the value of index is the last value. If not, return * back -1-------------------------------------------------/while (P.next!= null) {if (P.data.equals (e)) {index = K } k++; p = p.next; } if (P.data.equals (e)) {index = k;} return index; ///<summary>///To determine if the list is empty///</summary>///<returns></returns> public bool Empty () {return H EAD = null? True:false; }///<summary>///purge list///</summary> public void Clear () {head = null;}///<summary>///to group the list into groups/ </summary>///<returns> converted array </returns> public t[] ToArray () {t[] array = new T[count ()];//define a list with a long The same array/*------------------------------------------------* traverses the list, putting the value of each node in the list to the corresponding numberGroup------------------------------------------------*/node<t> p = head; int i = 0;//array subscript counter while (P.next!= null) {array[i++] = P.data; p = p.next;} array[count ()-1] = P.data; return array; ///<summary>///Add an array to the list///</summary>///<param name= "A" > To add an array of linked lists </param> public void add Range (t[] a) {//traverse the entire array, adding each element in the array as a new node in the list for (int i = 0; i < a.length; i++) {Add (a[i]);}///<summary> Delete all nodes in a list with a value of an element///</summary>///<param name= "E" > to delete the value of a node </param> public void Remove (T e) {//If the header The value of the pointer is equal to this element, delete the node and move the pointer back while (Head.data.Equals (e)) {head = Head.next}//If it is not a header pointer, remove the nodes node<t> p = head; while (P.next.next!= null) {if (P.next.data.equals (e)) {p.next = P.next.next; continue;} p = P.next;} if (P.next.data . Equals (e)) {p.next = null;}} <summary>///replaces all nodes in a list for a value with another value///</summary>///<param name= "A" > replaced value </param>/// <param name= "Second" > Replacement value </param> public void Replace (T-t second) {node<t> p = head; while (P.next!= null) {if (P.data.equals (a)) { P.data = second; } p = P.next; } if (P.data.equals (a) {p.data = second;}} <summary>///linked list inversion///</summary> public void Reverse () {node<t> p = head; Node<t> newhead = head; node<t> q = p; p = p.next; Newhead.next = null; while (P.next!= null) {q = p; p = p.next; q.next = newhead; newhead = q;} q = P; Q.next = Newhead; Newhead = p; head = Newhead; }} 

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.