What is the complexity of this algorithm? I am assuming it’s O(N) but I’d like some clarification.
If I had a tail in the linked list, I would assume this would be even faster since I would completely avoid having that while(current != null) loop to loop to the end of the list.
public void reverse() {
Stack<Node> stack = new Stack<Node>();
if (this.head != null || this.head.next != null) {
Node current = this.head;
while (current != null) {
stack.push(current);
current = current.next;
}
Node last = null;
while (!stack.empty()) {
if (last==null) {
this.head = stack.pop();
last = this.head;
continue;
}
last.next = stack.pop();
last = last.next;
if (stack.empty()) {
last.next = null;
}
}
}
}
You are pushing all the linked list elements onto stack by iterating the list this is one N then you iterate the stack which is another N so you Order notation in O(2N)
see how to reverse a list with O(1) space and O(n) time?