/** * @authorLuochengcheng * Define a single linked list*/ classNode {//variables Private intrecord; //point to Next object PrivateNode NextNode; PublicNode (intrecord) { Super(); This. Record =record; } Public intGetrecord () {returnrecord; } Public voidSetrecord (intrecord) { This. Record =record; } PublicNode Getnextnode () {returnNextNode; } Public voidSetnextnode (Node nextnode) { This. NextNode =NextNode; } } /** * @authorLuochengcheng * Two ways to achieve single-linked list reversal (recursive, normal) * Novice highly recommended to take the paper and pen next to the code drawing (easy to understand)*/ Public classReversesinglelist {/*** Recursive, reverses the next node before reversing the current node*/ Public Staticnode Reverse (node head) {if(NULL= = Head | |NULL==Head.getnextnode ()) { returnHead; } Node Reversedhead=Reverse (Head.getnextnode ()); Head.getnextnode (). Setnextnode (head); Head.setnextnode (NULL); returnReversedhead; } /*** Traverse to change the current node pointer after the next node of the current node is cached **/ Public Staticnode Reverse2 (node head) {if(NULL==head) { returnHead; } Node Pre=Head; Node cur=Head.getnextnode (); Node Next; while(NULL!=cur) {Next=Cur.getnextnode (); Cur.setnextnode (pre); Pre=cur; Cur=Next; } //set the next node of the original list's head node to NULL, and then assign the inverted head node to the headHead.setnextnode (NULL); Head=Pre; returnHead; } Public Static voidMain (string[] args) {Node head=NewNode (0); Node tmp=NULL; Node cur=NULL; //constructs a linked list of length 10 to hold the head node object head for(inti = 1; I < 10; i++) {tmp=NewNode (i); if(1 = =i) {head.setnextnode (TMP); } Else{cur.setnextnode (TMP); } cur=tmp; } //linked list before printing reversalNode h =Head; while(NULL!=h) {System.out.print (H.getrecord ()+ " "); H=H.getnextnode (); } //Call reversal MethodHead =Reverse2 (head); System.out.println ("\n**************************"); //results after printing is reversed while(NULL!=head) {System.out.print (Head.getrecord ()+ " "); Head=Head.getnextnode (); } } }
Java implements two methods of reversing a single list