This article describes two methods of unidirectional list inversion. Records, such as the following:
1.
Package Com.leetcode;public class Listreverse {public static void main (string[] args) {node Node1 = new Node (1); Node Node2 = new node (2); Node Node3 = new node (3); Node Node4 = new node (4); node1.next = Node2;node2.next = Node3;node3.next = Node4; Node head = reverse (Node1); while (head! = null) {System.out.println (head.val); head = Head.next;}} public static node reverse (node Head) {Node cur = head, post = Head.next;head.next = Null;while (post! = NULL) {node TMP = PO St;post = Post.next;tmp.next = Cur;cur = tmp;} return cur;} Static class Node{int Val; Node Next; Node (int val) {this.val = Val;this.next = null;}}}
The result of the execution is:
4321
2.
Package Com.leetcode;public class Listreverse {public static void main (string[] args) {node Node1 = new Node (1); Node Node2 = new node (2); Node Node3 = new node (3); Node Node4 = new node (4); node1.next = Node2;node2.next = Node3;node3.next = Node4; Node head = reverse (Node1); while (head! = null) {System.out.println (head.val); head = Head.next;}} public static node reverse (node Head) {Node dummy = new Node ( -1);d ummy.next = head; Node pre = dummy, cur = head, post = Head.next;while (post! = null) {Cur.next = Post.next;post.next = Pre.next;pre.next = PO St;post = Cur.next;} return dummy.next;} Static class Node{int Val; Node Next; Node (int val) {this.val = Val;this.next = null;}}}
The result of the execution is:
4321
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Java single-chain reversal