import java.util.Stack;
/* reverse head -> 1 -> 2 -> 3 -> 4 to head -> 4 -> 3 -> 2 -> 1
*
* 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 SolutionOne {
public static MyNode reverse(MyNode head) {
if(head == null) return head;
Stack<Integer> store = new Stack<>();
MyNode current = head;
while(current.next != null) {
current = current.next;
store.push(current.value);
}
current = head;
while(!store.isEmpty()) {
current.next = new MyNode(store.pop(), null);
current = current.next;
}
return head;
}
public static void main(String...args) {
MyNode head = createLinkedList();
MyNode preHead = new MyNode(0, head.next);
printResult(head);
head = reverse(head);
printResult(head);
printResult(preHead);
}
public static void printResult(MyNode head) {
if(head == null) return;
MyNode current = head;
System.out.println();
while (current.next != null) {
current = current.next;
System.out.print(current.value + " ");
}
}
public static MyNode createLinkedList() {
MyNode head = new MyNode(0, null);
MyNode next = new MyNode(1, null);
head.next = next;
next.next = new MyNode(2, null);
next = next.next;
next.next = new MyNode(3, null);
next = next.next;
next.next = new MyNode(4, null);
next = next.next;
next.next = new MyNode(5, null);
next = next.next;
next.next = new MyNode(6, null);
next = next.next;
return head;
}
}