我制作了一个Javascript函数来反转链表。但代码似乎产生了一个无限循环。请帮我找出这个错误。
reverse()
{
var current=this.head;
var prevNext=current.next;
this.tail.next=null;
this.tail=current;
while(current.next!==null)
{
var temp=prevNext;
if(temp.next!==null)
prevNext=temp.next;
temp.next=current;
current=temp;
}
this.head=current;
}
您进入了无休止的循环,因为在循环中您要分配temp.next
,然后将其分配给current,所以current.next
总是不是null
。
var current = this.head;
var previous = null;
var next = null;
while(current !== null)
{
next = current.next;
current.next = previous;
previous = current;
current = next;
}
this.head = previous;