我做了一个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;