public class LinkedNode { Integer id; LinkedNode next; public LinkedNode(Integer id) { this.id = id; } // 打印链表 public void print(){ System.out.print(this.id); if (this.next != null) { System.out.print("->"); this.next.print(); } else { System.out.println(); } } }
public class TestLinkedNode { public static void main(String[] args) { LinkedNode node1 = new LinkedNode(1); LinkedNode node2 = new LinkedNode(2); LinkedNode node3 = new LinkedNode(3); LinkedNode node4 = new LinkedNode(4); LinkedNode node5 = new LinkedNode(5); node1.next = node2; node2.next = node3; node3.next = Node4; node4.next = Node5; // print list System.out.println ( "list:" ); node1.print (); LinkedNode resNode = reverseList (node1); // list after printing System. out.println ( "chain after inversion is:" ); resNode.print (); } public static LinkedNode reverseList (LinkedNode node) { // If the list is empty or only a list of node need not process the IF (node == null || node.next == null ) { return Node; } //Statement of the current node, node predecessor and successor nodes LinkedNode CUR = the Node; LinkedNode pre = null ; LinkedNode the TEMP = null ; the while (! CUR = null ) { // first successor of the current node save up, because this value later change TEMP = cur.next; // inverted, the successor node is a node before the current relay node cur.next = pre; // the next movement of the pointer a succession of the former current node is a node pre = CUR; CUR = TEMP; } return pre; } }
operation result:
List:
1-> 2-> 3-> 4-> 5
list after inversion is:
5-> 4-> 3-> 2-> 1