/* reverse linked list 1 -> 2 -> 3 -> 4 to 4 -> 3 -> 2 -> 1
* notice there is no head node
*
* in place reverse
*
* step 1. change the node 1's next to null
* step 2. change node 2's next to node 1
* step 3. change node 3's next to node 2
* ...
* finally. return the address of node 4
*
* The reverse method traversals the linked list once,
* the time complexity is O(N).
*
* This solution didn't create a new linked list, it changes the node's next value in place,
* the space complexity is O(1).
*
* */
public class ExtendSolutionFour {
public static MyNode reverse(MyNode head) {
if(head == null || head.next == null) return head;
MyNode pre = head;
MyNode current = head.next;
MyNode next = null;
//special treatment for the tail
pre.next = null;
while(current != null) {
//store next node before change the pointer
next = current.next;
//point the current node to previous node
current.next = pre;
//advance the previous node
pre = current;
//advance the current node
current = next;
}
return pre;
}
public static void main(String...args) {
MyNode head = createLinkedList();
MyNode preHead = new MyNode(head.value, head.next);
printResult(head);
head = reverse(head);
printResult(head);
printResult(preHead);
}
public static void printResult(MyNode head) {
System.out.println();
if(head == null) return;
while(head != null) {
System.out.print(head.value + " ");
head = head.next;
}
}
public static MyNode createLinkedList() {
MyNode head = new MyNode(1, null);
MyNode current = head;
for(int i = 2; i <= 4; i++) {
current.next = new MyNode(i, null);
current = current.next;
}
return head;
}
}