/** * @author Luochengcheng * Defines a single-linked list */class Node {//variable private int record; Point to the next object private Node NextNode; Public Node (int record) {super (); This.record = record; } public int Getrecord () {return record; public void Setrecord (int record) {This.record = record; } public Node Getnextnode () {return nextnode; } public void Setnextnode (Node nextnode) {this.nextnode = NextNode; }}/** * @author Luochengcheng * 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 class Reverse singlelist {/** * recursive, reverses the next node before reversing the current node */public static node reverse (node head) {if (n ull = = Head | | Null = = Head.getnextnode ()) {return head; } Node reversedhead = reverse (Head.getnextnode ()); Head.getnextnode (). Setnextnode (head); Head.setnextnodE (null); return reversedhead; }/** * Traversal, the next node of the current node is cached after the current node pointer is changed * */public static node Reverse2 (node head) { if (null = = head) {return head; } 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, then assign the inverted head node to head head.setnextnode (NULL); head = Pre; return head; } public static void Main (string[] args) {node head = new Node (0); Node tmp = NULL; Node cur = null; Constructs a linked list of length 10, holds the head node object head for (int i = 1; i < i++) {tmp = new Node (i); if (1 = = i) {head.setnextnode (TMP); } else { Cur.setnextnode (TMP); } cur = tmp; }//Print the list before reversal Node h = head; while (null! = h) {System.out.print (H.getrecord () + ""); h = H.getnextnode (); }//Call reversal Method head = Reverse2 (head); System.out.println ("\n**************************"); Prints the inverted result while (null! = Head) {System.out.print (Head.getrecord () + ""); Head = Head.getnextnode (); } } }
Flip single-linked list of Java basics