使用JavaScript反向链接列表,该功能不起作用

问题描述 投票:0回答:1

我做了一个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;
    }
javascript linked-list nodes reverse singly-linked-list
1个回答
0
投票

您进入无穷循环,因为在循环中您正在分配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;
© www.soinside.com 2019 - 2024. All rights reserved.