如何确定这两个双链表算法的空间和时间复杂度?

时间:2016-05-31 08:44:17

标签: java algorithm time-complexity big-o space-complexity

我解决了下一个有两个解决方案的练习:https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list

首先(非递归):

/*
  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 == null) return null;

    Node current = head;

    while (current.next != null) {
        Node temp = current.next;
        current.next = current.prev;
        current.prev = temp;

        current = temp;
    }

    current.next = current.prev;
    current.prev = null;

    return current;
}

第二种算法(递归):

/*
  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;
}

根据这本书,解决方案必须是O(n)。我想使用递归解决方案更优雅,但也许我错了。你能帮助确定这两个算法的空间和时间复杂度,还是你的,这在性能上更好?

1 个答案:

答案 0 :(得分:1)

问题有点不清楚,两种解决方案在时间和空间上似乎都是O(n)。虽然你可以删除特殊情况并让Torvalds高兴。类似的东西:

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);

}

我没有测试过这些,仅将它们用作灵感。 (如果head在开头为null,则递归将为nullpointer。)

相关问题