【问题标题】:time complexity of reversing a linked list反转链表的时间复杂度
【发布时间】:2015-11-18 17:43:58
【问题描述】:

我编写了以下函数来反转链表,并且想知道“交换”的时间复杂度。我的理由如下: 它是 o(n)

链表中的插入/删除是 o(1),但这假设只是添加到尾部或从头部/尾部删除。在这里,您正在迭代和访问每个元素,并且访问链表中的元素是 o(n)。 那是对的吗?一般来说,swap的时间复杂度是多少?

LinkedList.prototype.reverse = function () {
  var previous = null;
  var current = this.head;
  var next;
  while (current) {
    //swap pointers
    //cache iteration/temp var
    next = current.next;
    //point the next to the previous
    current.next = previous;
    //previous is the current one
    previous = current;

    //iterate
    current = next;
  }
  //after you're done set the head to null (ie make it the tail)
  this.head = null;
};

【问题讨论】:

  • 为什么反向完成后linkedList的头部设置为null?不应该是尾元素吗?如果头部为空,如何迭代链表?
  • 由于链表现在被反转了头部现在是尾部:) 反转完成后,你不需要再迭代了。
  • ok...也许这是你业务的需求,我只是觉得linkedlist应该是reverse后的linkedlist

标签: javascript algorithm data-structures


【解决方案1】:

链表算法的时间复杂度将取决于你是否从链表中要操作的地方开始。

如果你知道插入/删除是 O(1),如果你必须迭代才能找到它,那么插入/删除是 O(n)。

swap 也是如此。

反转单链表是 O(n),因为您必须触及每个节点。有一个数据结构技巧,反转双向链表是 O(1)。你用一点来保持哪个方向算“前进”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 2023-02-07
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2019-07-02
    相关资源
    最近更新 更多