【发布时间】: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