import java.util.*;
/* reverse linked list 1 -> 2 -> 3 -> 4 to 4 -> 3 -> 2 -> 1
* notice there is no head node
*
* reverse with the help of a stack
*
* step 1. traversal the linked list, push the elements into stack
* step 2. traversal the stack, pop the elements and create a linked list
*
* The reverse method traversals the linked list once to fill the stack,
* then it traversals the stack once to create the reversed linked list,
* the time complexity is O(N).
*
* This solution preserves original linked list, it also uses an extra stack,
* the space complexity is O(N).
*
* */
public class ExtendSolutionOne {
public static MyNode reverse(MyNode head) {
if(head == null || head.next == null) return head;
Stack<MyNode> store = new Stack<>();
MyNode current = head;
while(current != null) {
store.push(current);
current = current.next;
}
MyNode newHead = new MyNode(store.pop().value, null);
current = newHead;
while(!store.isEmpty()) {
current.next = new MyNode(store.pop().value, null);
current = current.next;
}
return newHead;
}
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;
}
}