Linked list of data structures

Source: Internet
Author: User

A linked list is a data structure that is faster to insert and delete, with the disadvantage of finding it relatively slowly. Unless you need to frequently use subscript to randomly access the data, or in many uses of the array can be used to replace the list

In a linked list, each data item is contained in a chain node , and a link is an object of a class. Each chain node object contains a reference to the next link point, and the list itself has a field in the object that points to the first link node, as shown in:


In the array, each item occupies a specific position, which can be accessed directly with a lower label, like a row of houses, where you can find specific opinions based on the room number. In a linked list, the only way to find a particular element is to keep searching along the chain of elements to find the data item you're looking for.

Single linked list

The deletion of a linked list specifies the link node, by pointing to the next link node of the target chain node by the next pointer to the last link node of the target link, as follows:


In this way, the linked list of pointers in the chain will be skipped with the deleted elements, to achieve the purpose of deletion. However, the next pointer to the removed element actually points to the original next element, except that it cannot be retrieved from the linked list, and the garbage collection mechanism of the JVM will recycle it after a certain amount of time

Adding a link node is a bit more complicated than deleting it, first we want the next pointer to the link node before the insertion position to point to the target link, and then the next pointer of the target link point to the chain node after the insertion position. The insertion position in this example is limited to the first position of the linked list, as follows:

The following gives the implementation class for a single-linked list

The wrapper class for the link node is public class, link {public int: age;      public String name;  Public Link Next;             The next link node that points to the link//Construction method Public link (int age,string name) {this.age = age;      THIS.name = name;      }//Print information about the link node public void DisplayLink () {System.out.println ("Name:" +name+ ", Age:" +age);  }}//List encapsulation class public class Linklist {private link first;      Point to the first link node in the list public linklist () {primary = null;             }//Insert to the front of the list public void Insertfirst (link link) {link.next = first;      first = link;                    }//delete the first link node, return the deleted link node reference public link Deletefirst () throws exception{if (IsEmpty ()) { throw new Exception ("The list is empty!             Unable to delete operation ");             Link temp = first;             first = First.next;      return temp;             }//Print out all the list elements public void Displaylist () {link cur = first; WhIle (cur! = null) {//loop print each link node cur.displaylink ();             Cur= Cur.next;             }}//delete the link node for the specified value of the property, public link Delete (int key) {link = null;             Link cur = first;             Link next = First.next;             Link previous = null;                           while (cur! = null) {if (Cur.age = = key) {//found the link node to delete link = cur;                                   If the precursor of the current chain node is null, it proves that when it is the first link node of the linked list, it needs to be re-assigned if (previous ==null) after the link node is deleted.                           This.first =next; }else{//delete operation, the next pointer of the precursor is pointed to the next of the current link node, the list will go to the current link node this ring prev                           Ious.next= Next;                    } break;                    }else if (Cur.next ==null) {//The current link node is not a target and the next link node is null, proving that there is no link break to delete;                      }                 The current link node is not the target to be deleted, then go back to look for next = Next.next;                    cur = cur.next;             previous = cur;      } return link;             }//Find the link node with the specified value for the public link find (int key) {link link = null;             Link cur = first;             Link next = null;             Link previous = null;                           while (cur! = null) {if (Cur.age = = key) {link = cur;                    Break                    }else if (Cur.next = = null) {//The current link node is not the target to be found and the next link is null, it proves that no target break was found;                    }//The current link is not the target you are looking for and there is the next link, then go back and look for next = Next.next;                    cur = cur.next;             previous = cur;      } return link;      }//Empty public boolean isEmpty () {return (first = = null); }     }

Double-ended linked list

First of all, it is important to note that two -ended linked list and doubly linked list are completely different concepts

The difference between a double-ended list and a single-linked list is that it is not only a reference to the first node, but also a reference to the last link, as shown in:


A reference to the last link allows a link to be inserted at the end of the table like a header, and using a double-ended list is more appropriate for situations where a single-linked list is not easy to operate, and the implementation of the queue is the case

The following is the implementation class for a doubly-linked list, unlike a single-linked list, where the Doubleendlist class has more references to the footer and more actions to insert the footer

Package class public class Doubleendlist {Private link first for double-ended list;   Point to the first link node in the list private link last;             Point to the last link node in the list public doubleendlist () {first = null;      last = null;                    }//Insert to the front of the list public void Insertfirst (link link) {if (IsEmpty ()) {///If it is an empty list, the first node inserted is both a table header and a footer             last = link;             } link.next = First;      first = link;                    }//inserted at the end of the list public void Insertlast {if (IsEmpty ()) {///If it is an empty list, the first node inserted is both a table header and a footer             first = link;             }else{last.next = link;      } last = link;                    }//delete the first link node, return the deleted link node reference public link Deletefirst () throwsexception{if (IsEmpty ()) { throw new Exception ("The list is empty!             Unable to delete operation ");             Link temp = first;  if (First.next = = null) {last = null; If there is only one link node, the deletion will affect the lastpointer} first = First.next;      return temp;             }//Print out all the list elements public void Displaylist () {link cur = first;                    while (cur! = null) {//loop prints each link node cur.displaylink ();             cur = cur.next;      }}//Empty public boolean isEmpty () {return (first = = null); }     }

The double-ended list can be inserted at the end of the table, but it is still not easy to delete the footer, because we do not have a way to quickly get the second-to-last link, the double-ended linked list does not have a reverse pointer, which is to rely on a doubly linked list to solve the

Ordered linked list

For some applications, it is useful to keep the data in order in a linked list, which is called "ordered list".

In general, the deletion of an ordered list is limited to the maximum or minimum value, but sometimes a particular point is also found and deleted, but this operation is inefficient for an ordered list

An ordered list is better than an ordered array in that it is more efficient to insert (no need to move elements like an array), and the list can be flexibly scaled, and the size of the array is fixed. But the improvement of efficiency and the advantage of flexibility are at the cost of the complexity of the algorithm.

Below we give an ordered single-linked list implementation class

The package class public class SortedList {Private link first of the ordered list;      Point to the first link node in the list public SortedList () {primary = null;             }//Insert public void Insert (link link) {link previous = null;             Link cur = first;                    while (cur! = null &&link.age>cur.age) {//lists are arranged from large to small previous = cur;             cur = cur.next;             if (previous = = null) {//If previous is null, it proves that the current link node is the table header This.first = link;             }else{previous.next = link;                  } link.next = cur;                    }//delete the first link node, return the deleted link node reference public link Deletefirst () throwsexception{if (IsEmpty ()) { throw new Exception ("The list is empty!             Unable to delete operation ");             Link temp = first;             first = First.next;      return temp;     }//Print out all the linked list elements public void Displaylist () {        Link cur = first;                    while (cur! = null) {//loop prints each link node cur.displaylink ();             cur = cur.next;      }}//Empty public boolean isEmpty () {return (first = = null); }     }

The difference between the implementation class and the single-linked list is that the insert operation is sequential, so you need to find the location to insert before inserting

An ordered list can be used in an efficient sorting mechanism. Suppose there is an unordered array, and if the data from this array is inserted into an ordered list, they are automatically sorted in order and then re-placed into the array from the ordered list, and the array becomes an ordered array. This sort method is more efficient than the usual insertion sort in an array, because it is less replicated in this way

Doubly linked list

Here's a more complex list structure: A doubly linked list.

A potential problem with traditional linked lists is that there is no reverse reference, it is easy to jump from the previous link to the next one, and it is difficult to jump from the next link to the previous link node.

A doubly linked list provides this ability to allow for sequential traversal and also for backward traversal. The key to implementing this feature is that each link node has a reference to the next link node, as well as a reference to the previous link, as shown in:


Admittedly, the two-way list has its own advantages, but any advantage has to pay a certain price, such as the two-way list insertion and deletion will become more complex, because at the same time to handle double pointer changes. For example, we do a table header insert as follows:


Similar to the footer insertion, which is the mirroring operation of the table header insert

Insert a new link node at a location other than the footer of the table header as follows:


For a delete operation, if you want to delete the table header or footer, it is relatively simple, if you want to delete the specified value of the link node is more complex, first need to locate the link to delete, and then change its front and back link node pointer, as follows:


The following gives the implementation class of the doubly linked list, unlike the previous list of links, the wrapper class needs to make some changes, the previous chain node class only contains the backward reference to next, in the doubly linked list also need to join the forward reference previous

The wrapper class for the link node is public class, link {public           int: age;      public String name;      Public Link next;  Point to the next link public      link previous;  Point to Previous link           //construction method public      link (int age,string name) {             this.age = age;             this.name = name;      }           Print the link node information public      void DisplayLink () {             System.out.println ("Name:" +name+ ", Age:" +age);}      }

Two-way chain list Encapsulation class public class Doublelylinklist {private link first;   Point to the first link node in the list private link last;             Point to the last link in the list public doublelylinklist () {first = null;      last = null;                    }//Insert to the front of the list public void Insertfirst (link link) {if (IsEmpty ()) {///If it is an empty list, the first node inserted is both a table header and a footer             last = link;             }else{//If it is not an empty list, the first pointer of the linked list points to the link first.previous = link;             } link.next = First;      first = link;                    }//inserted at the end of the list public void Insertlast {if (IsEmpty ()) {///If it is an empty list, the first node inserted is both a table header and a footer             first = link;                    }else{last.next = link;             Link.previous = Last;      } last = link;                    }//delete the first link node, return the deleted link node reference public link Deletefirst () throws exception{if (IsEmpty ()) { throw new Exception ("The list is empty! Unable to delete operation ");             Link temp = first;  if (First.next = = null) {last = null;  If there is only one link, the deletion will affect the last pointer}else{//If there are at least two link nodes, then the previous of the second link node is set to null first.next.previous             = NULL;             } first = First.next;      return temp;                    }//delete the last link node, return the deleted link node reference public link Deletelast () throws exception{if (IsEmpty ()) { throw new Exception ("The list is empty!             Unable to delete operation ");             Link temp = last;  if (last.previous = = null) {first = null;  If there is only one link, then the first pointer}else{//If there are at least two link nodes will be deleted, then the next second node of the penultimate link is set to null Last.previous.next =             Null             } last = last.previous;      return temp;             }//Find the link node with the specified value for the public link find (int key) {link cur = first; while (cur! = NULL &&cur.age! = key) {if (Cur.next = = null){returnnull;             The current link node is not the target you are looking for and has reached the end of the table} cur = cur.next;      } return cur; }//After the specified link node is inserted, the operation returns True successfully, the operation fails to return False public boolean InsertAfter (link) {Link target = find             (Link.age);             Boolean flag = true;             if (target = = null) {//did not find the inserted reference chain node flag = false;                    }else{//found the inserted reference chain node if (Target.next = = null) {//reference chain node is the footer insertlast (link);                           }else {//The list has at least two link nodes target.next.previous= link;                           Link.next =target.next; The above two steps must be performed in order to perform the following two steps//the above two steps deal with link and its next link node relationship//The following two steps to deal with link and its previous link node off                           Department target.next = link;                    Link.previous =target;                       }             }         return flag;             }//Print out all the list elements public void Displaylist () {link cur = first;                    while (cur! = null) {//loop prints each link node cur.displaylink ();             cur = cur.next;      }}//Empty public boolean isEmpty () {return (first = = null); }     }


Linked list of data structures

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.