There is a small need to implement a two-way list reversal Then there is the code below:
Linked list element structure definition:
PackageCom.util; Public classLinkednode<t>{ PrivateT value; PrivateLinkednode<t>prev; PrivateLinkednode<t>Next; PublicLinkednode (T value, linkednode<t> prev, linkednode<t>next) { Super(); This. Value =value; This. prev =prev; This. Next =Next; } PublicT GetValue () {returnvalue; } Public voidSetValue (T value) { This. Value =value; } PublicLinkednode<t>GetPrev () {returnprev; } Public voidSetprev (linkednode<t>prev) { This. prev =prev; } PublicLinkednode<t>GetNext () {returnNext; } Public voidSetnext (linkednode<t>next) { This. Next =Next; } }
Linked List definition:
PackageCom.util; Public classLinkedlist<t>{ Private transient intSize=0; Private transientLinkednode<t> first=NULL; Private transientLinkednode<t> last=NULL; /*** Add elements to the doubly linked list header **/ Public voidAddFirst (T t) {Linkednode<T> Oldfirst =First ; Linkednode<T> NewNode =NewLinkednode<t> (T,NULL, Oldfirst); First=NewNode; if(Oldfirst = =NULL) Last=NewNode; ElseOldfirst.setprev (NewNode); Size++; } /*** Convert a doubly linked list into a unary array: from the beginning to the tail. * */ Publicobject[] ToArray () {object[] result=NewObject[size]; inti = 0; for(linkednode<t> node = first; Node! =NULL; node =Node.getnext ()) Result[i++] =Node.getvalue (); returnresult; } /*** Reverse Rotation **/ Public voidreverse () {if(first==NULL|| last==NULL) return; Linkednode<T>prev; Linkednode<T>Next; Linkednode<T> newfirst=NULL; Linkednode<T> newlast=NULL; for(linkednode<t> node = first; Node! =NULL; node =Node.getprev ()) {prev=Node.getprev (); Next=Node.getnext (); if(Node.getprev () = =NULL) {Newlast=node; }Else if(Node.getnext () = =NULL) {Newfirst=node; } node.setnext (prev); Node.setprev (next); } First=Newfirst; Last=Newlast; }}
Note: Here the main implementation of the three functions, in the list of links to add elements, toarray functions, inversion functions, in fact, the list should contain other functions: add elements at the end, insert elements, index, remove, traverse and so on.
Test code:
Importcom.util.LinkedList; Public classLinkedlisttest { Public Static voidMain (string[] args) {LinkedList<String> list=NewLinkedlist<string>(); List.addfirst ("5"); List.addfirst ("3"); List.addfirst ("1"); for(Object String:list.toArray ()) {System.out.println (string); } System.out.println ("-------------------------------start to reverse-------------------------------"); List.reverse (); System.out.println ("-------------------------------the end of the reverse-------------------------------"); for(Object String:list.toArray ()) {System.out.println (string); } }}
Java: Bidirectional linked list inversion implementation