这个算法的复杂度是多少?我假设它是 O(N) 但我想澄清一下。如果我在链表中有一个尾巴,我会假设这会更快,因为我会完全避免让 while(current != null) 循环循环到链表的末尾。
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;
}
}
}
}