繁体   English   中英

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

[英]How to determine the space and time complexity of these two double linked list algorithms?

我解决了下一个练习,有两个解决方案: 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)。 我想使用递归解决方案更优雅,但也许我错了。 你能帮忙确定这两种算法的空间和时间复杂度,或者你的,哪个性能更好?

问题有点不清楚,两个解决方案在时间和空间上似乎都是 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 在开始时为空,则递归也会为空指针)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM