【发布时间】:2012-08-16 22:07:08
【问题描述】:
这个算法的复杂度是多少?我假设它是 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;
}
}
}
}
【问题讨论】:
-
您应该提出一个明确的问题,告诉我们您期望的答案。
-
我重新编辑了它,但本质上我是在问这个算法的运行时间复杂度是多少
-
是的,它是 O(n*constant),即 O(n),假设 java Stack push 和 pop 是 O(1),恰好是这种情况。您的空间复杂度也是 O(n),并且有一些方法可以在空间复杂度 O(1) 中做到这一点。
标签: java algorithm complexity-theory