【问题标题】:Reversing a linked list using JavaScript, the function doesn't work使用JavaScript反转链表,该功能不起作用
【发布时间】:2020-06-15 20:38:30
【问题描述】:

我制作了一个 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】:

    您进入无限循环,因为在循环内您分配temp.next,然后将其分配给当前,所以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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 2018-10-30
      • 2019-07-27
      • 2019-07-29
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多