Java 如何确定这两种双链表算法的空间和时间复杂度?
我用两种解决方案解决了接下来的练习: 第一(非递归): 第二种算法(递归):Java 如何确定这两种双链表算法的空间和时间复杂度?,java,algorithm,time-complexity,big-o,space-complexity,Java,Algorithm,Time Complexity,Big O,Space Complexity,我用两种解决方案解决了接下来的练习: 第一(非递归): 第二种算法(递归): 根据这本书,解必须是O(n)。我想使用递归解决方案更优雅,但也许我错了。您能帮助确定这两种算法的空间和时间复杂度吗?或者在您的示例中,哪种算法的性能更好?问题有点不清楚,两种解决方案在时间和空间上似乎都是O(n)。尽管你可能会移除这些特殊情况,让托瓦尔兹高兴。比如: Node Reverse(Node head) { if (head == null) return null; Node current =
根据这本书,解必须是O(n)。我想使用递归解决方案更优雅,但也许我错了。您能帮助确定这两种算法的空间和时间复杂度吗?或者在您的示例中,哪种算法的性能更好?问题有点不清楚,两种解决方案在时间和空间上似乎都是O(n)。尽管你可能会移除这些特殊情况,让托瓦尔兹高兴。比如:
Node Reverse(Node head) {
if (head == null) return null;
Node current = head;
while (current != null) {
Node temp = current.next;
current.next = current.prev;
current.prev = temp;
current = temp;
}
return current;
}
}
我没有测试过这些,只是把它们当作灵感。(如果head在开始时为null,则递归指针也将为null)
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node Reverse(Node head) {
if (head.next == null) {
head.next = head.prev;
head.prev = null;
return head;
}
Node newHead = Reverse(head.next);
Node temp = head.next;
head.next = head.prev;
head.prev = temp;
return newHead;
}
Node Reverse(Node head) {
if (head == null) return null;
Node current = head;
while (current != null) {
Node temp = current.next;
current.next = current.prev;
current.prev = temp;
current = temp;
}
return current;
Node Reverse(Node head) {
Node temp = head.next;
head.next = head.prev;
head.prev = temp;
return temp==null?head:Reverse(temp);