Data structure Java implementation----Loop chain list, simulation chain list

Source: Internet
Author: User

Tag: Represents the emulation of your own tar state Insert description I+1 IDE

    • One-way circular linked list
    • Bidirectional loop Linked List
    • Simulation Chain List

One, one-way circular chain list:

1. Concept:

One-way circular linked list is another form of a single-linked list, and its structure is that the pointer to the last node in the list is no longer the end tag, but instead points to the first node of the entire list, thus making the single-linked list form a ring.

Compared with the single-linked list, the advantages of the circular single-linked list are more convenient from the chain end to the chain head. When a sequence of data elements to be processed has a ring-shaped structure, it is appropriate to use a circular single-linked list.

The same as the single-linked list, the circular single-linked list also has the lead node structure and not the lead node structure two, the leading node of the circular single-linked list implementation of the insertion and deletion operations, the algorithm is more convenient to implement.

The operation implementation method of the loop single-linked list of the leading node and the operation implementation method of the single-linked list with the leading node are similar, the difference is only:

(1) In the constructor, to add a head.next = Head statement, the initial lead node of the cycle of the single-linked list is designed to the state shown in (a).

(2) in the index (i) member function, the loop end judgment condition current! = NULL is changed to the current! = head.

2, single-linked list code implementation:

First review the previous article, positioning to the third paragraph "three, single necklace table code implementation", we need to modify this paragraph (3) Linklist.java code, (1) and (2) the code is unchanged.

(3) Linklist.java: Single Loop List class: (Core code)

 1//Unidirectional Circular List Class 2 public class Cyclelinklist implements list {3 4 node head;//Head Pointer 5 node current;//current node Object 6 in T size;//number of Nodes 7 8//Initialize an empty list 9 public cyclelinklist () 10 {11//Initialize the head node so that the head pointer points to the head node. and make the current node object equal to the head node. This.head = current = new Node (null), This.size =0;//one-way linked list, initial length is zero. This.head.next = this.head;15}16 17//positioning function to implement the previous node of the current operand, that is, to position the current node object to the previous node to manipulate the node.     18//For example, we want to a2 this node before the insertion operation, it is to locate the current node object to the A1 node, and then modify the A1 node's pointer field, the public void Index (int index) throws Exception20 {+ if (index <-1 | | | index > SIZE-1) @ {Exception "parameter Error!    "); 24}25//description operate after the head node. if (index==-1)//Because the subscript of the first Data element node is 0, then the subscript of the head node is naturally-1. return;28 current = head.next;29 int j=0;//loop variable (current! = head&&j& Lt;index) {current = Current.next;33 j++;34}35 36} 37     @Override39 public void Delete (int index) throws Exception {//TODO auto-generated method Stub4 1//Determine if the linked list is null if (IsEmpty ()) () () () () () () () (the "list is empty, cannot be deleted!") ");}46 if (Index <0 | | Index >size) ("Parameter Error!") ");}50 index (INDEX-1);//Navigate to the previous node object to manipulate the node. Wuyi Current.setnext (current.next.next); size--;53}54 @Override56 public Object get (int in         Dex) throws Exception {//TODO auto-generated Method stub58 if (Index <-1 | | index >size-1) 59 {$ throw new Exception ("argument is illegal!     ");}62 index (index), current.getelement return ();}66 @Override68 public void Insert (int index, Object obj) throws Exception {the//TODO auto-generated method stub70 if (in Dex <0 | | Index >size) (New ExceptiOn ("Parameter error! ");}74 index (INDEX-1);//Navigate to the previous node object to manipulate the node. Current.setnext (New Node (Obj,current.next)), size++;77}78 @Override80 public boolean IsEmpty () {bayi//TODO auto-generated method stub82 return size==0;83}84 @Override85 public in T size () {//TODO auto-generated method stub87 return this.size;88}89 90 91}

Line 14 is the code that is added, and 30 lines is the modified code.

3. Application examples of single-cycle chain list:

Write a small game of drumming and spreading flowers.

The rules of the game: N People in a circle, from the first person began to transmit flowers, when the number of M, the person quit the game until the last person left.

Code implementation:

(4) Game.java:

 1//Game Class 2 public class Game {3 4//One-way loop linked list 5 cyclelinklist list = new Cyclelinklist (); 6//Total number 7 int num ;        8//Count to a few exits 9 int key;10 11//Game initialization method (int num,int key)-{This.num = num;15 This.key = key;16}17 public void Play () throws Exception19 {(int i=0;i<num;i++)  {List.insert (I, I); }24 System.out.println ("\ n-------before the game starts---------\ n"); 2 for (int i=0;i<list.size;i++) 7 {System.out.print (List.get (i) + ")}30 System.out.println (" \ n-------game starts---------\ n "); icount=num int; Start equals total number num32 int j=0; Accumulator, the calculation can be divisible by key. The node node = list.head;35 while (icount!=1). {PNs (node.getelement ()!=null&amp  ;& Integer.parseint (Node.getelement (). toString ())!=-1) (j);    if (j%key==0) 41 {42             Node.setelement ( -1); icount--;44 System.out.println ();                 R (int i=0;i<list.size;i++) System.out.print {list.get (i) + ""); 48 }49}50} node = node.next;52}53 System.out.println ("\ n-------game is over---- -----\ n "); i=0;i<list.size;i++ for (int) System.out.print (List.get (i) +" "); 57}5 8}59 60}

(5) Test.java:

1 public class Test {2  3     /** 4      * @param args 5      */6 public     static void Main (string[] args) throws Exc eption {7         //TODO auto-generated Method Stub 8/       * 9       cyclelinklist list = new Cyclelinklist ();       i=0;i<10;i++) each       {          int temp = ((int) (Math.random () *100))%100;13          List.insert (i, temp);          System.out.print (temp+ "");       }16       List.delete (4);       System.out.println ("\ n------after removing the Fifth Element------- ") for       (int i=0;i<list.size;i++),       {           System.out.print (list.get (i) +" ");       }*/22         Game       game = new Game (10,3);       game.play ();     }27}

Two, two-way circulation chain list:

Doubly linked list:

A doubly linked list is each node with a precursor pointer in addition to the successor pointer. And the single-linked list, the two-way list also has the lead node structure and not the lead node structure, the leading node of the doubly linked list is more commonly used; In addition, the two-way list can also have both circular and non-cyclic structure, circular structure of the doubly linked list is more commonly used.

Two-way loop linked list:

In a doubly linked list, each node consists of three fields, namely the element field, the next field, and the prior domain, where the element field is the data element field, the next field is the object reference to the successor, and the prior field is the object reference to the predecessor node. Diagram structure for a doubly linked list node:

As the leading node of the two-way circular linked list diagram structure. The next and Prior of the two-way loop list each form their own one-way circular chain list:

In the doubly linked list, there is the following relationship: The Set object reference p represents the first node in a doubly linked list, then P.next represents the I+1 node, and P.next.prior still represents the first node, that is, p.next.prior = = p; P.prior represents the I-1 node, P.prior.next still represents the first node, that is, p.prior.next = = P. Is the diagram of the two-way linked list above:

The insertion process for a bidirectional loop list:

The pointer in P indicates where to insert the node, S represents the node to be inserted, ①, ②, ③, ④ represent the steps to implement the insertion process:

The removal process for a circular doubly linked list:

The pointer in P indicates where to insert the node, ①, ② represents the steps to implement the delete process:

2, two-way loop linked list code implementation:

(1) List.java:

1//Linear Table Interface 2 public interface List {3     //Get linear table length 4 public     int size (); 5  6     //Determine if the linear table is empty 7 public     Boolean IsEmpty (); 8  9     //Insert element Ten public     void Insert (int index, Object obj) throws exception;11     //delete element public     void Delete (int index) throws exception;14     //Gets the element at the specified position. Public     Object Get (int index) throws exception;17}

(2) Node.java:

 1//Node Class 2 public class Node {3 4 Object element;//data field 5 Node next; Successor pointer Field 6 Node prior; Precursor pointer field 7 8//Head node construction Method 9 Public node (node nextval) {This.next = nextval;11}12 13//Non-head node construction Method 1     4 Public Node (Object obj, node nextval) {this.element = obj;16 This.next = nextval;17}18 19  Get the successor node of the current node, public node GetNext () {this.next;22}23 24//Get the current node's predecessor node Getprior () {this.prior;27}28 29//Gets the value of the current data field. Public Object getelement () {Retu RN this.element;32}33 34//Set the subsequent pointer field of the current node to the public void Setnext (Node nextval) {this.next = Nextval;3     7}38 39//Set the precursor pointer field for the current node Setprior (node Priorval) {This.prior = priorval;42}43 44 Sets the data field for the current node, public void SetElement (Object obj) {this.element = obj;47}48-Public String t Ostring () {return this.elemenT.tostring (); 51}52} 

(3) Doublecyclelinklist.java:

 1//Unidirectional List Class 2 public class Doublecyclelinklist implements List {3 4 node head;//Head Pointer 5 node current;//current Node Object 6 int size;//Number of nodes 7 8//Initialize an empty list 9 public doublecyclelinklist () {10//Initialize the head node, so that the head pointer points to the head node. and make the current node object equal to the head node. This.head = current = new Node (null), this.size = 0;//one-way linked list, initial length is zero. This.head.next = head;14 This.head.prior = head;15}16 17//positioning function to implement the previous node of the current operand, that is, to have the current node object positioned to the The previous node of the node.             public void index (int index) throws Exception {if (Index <-1 | | index > SIZE-1) {20 throw new Exception ("Parameter Error! 21}22//Description after the head node operation. if (index = =-1) return;25 current = head.next;26 Int j = 0;//loop variable Whil     E (current! = Head && J < index) {current.next;29 = j++;30}31 32 }33 @Override35 public void Delete (int index) throws Exception {//TODO Auto-generatEd method stub37//Determine if the linked list is empty if (IsEmpty ()) {The new Exception ("The linked list is empty and cannot be deleted!") ");}41 if (Index < 0 | | | Index > Size) {$ throw new Exception ("Parameter Error! ");}44 index (INDEX-1);//Navigate to the previous node object to manipulate the node.     Current.setnext (Current.next.next); Current.next.setPrior (current); size--;48}49 50 @Override51 public Object get (int index) throws Exception {//TODO auto-generated method Stub53 I F (Index <-1 | | index > SIZE-1) {si throw new Exception ("argument is illegal! ");}56 index (index); current.getelement}60 @Override62 Public void Insert (int index, Object obj) throws Exception {//TODO auto-generated Method stub64 if (index &lt ; 0 | | Index > Size) {Exception new ("Parameter Error!) ");}67 index (INDEX-1);//Navigate to the previous node object to manipulate the node. Current.setnext(New Node (obj, Current.next)), Current.next.setPrior (current), Current.next.next.setPrior (Current.next ); size++;73}74 @Override76 public boolean isEmpty () {metho//TODO auto-generated D stub78 return size = = 0;79}80 bayi @Override82 public int size () {//TODO auto-generated m Ethod stub84 return this.size;85}86 87 88}

(4) Test.java:

1 public class Test {2  3     /** 4      * @param args 5      */6 public     static void Main (string[] args) throws Exc eption {7         //TODO auto-generated method stub 8         doublecyclelinklist list = new Doublecyclelinklist (); 9 for         (i NT i = 0; I < 10;  i++) {ten             int temp = ((int) (Math.random () *))% 100;11             list.insert (i, temp);             System.out.print (temp + "");         }14         List.delete (4);         System.out.println ("\ n------Delete the Fifth element after-------"); + for         (int i = 0; i < list.size; i++) {             System.out.print (list.get (i) + ");         }19     }20 21}

Operating effect:

Three, the simulation chain list:

In a chained storage structure, we implement order relationships between data elements by relying on pointers. We can also use arrays to construct simulation lists. The method is to add a variable field (or two) of type int to the array that represents the subscript of the latter (or previous) data element in the array. The pointers we construct for these types of int variables are called simulation pointers. This allows the simulation of a single-linked list (or a simulated doubly linked list) to be constructed with a simulation pointer.

Data structure Java implementation----Loop chain list, simulation chain list

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.