RISHABH SINGH
RISHABH SINGH

Reputation: 11

Reversing a linked list using JavaScript, the function doesn't work

I made a Javascript function to reverse a linked list. But the code seems to produce an infinite loop. Please help me figure out the bug.

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;
    }

Upvotes: 0

Views: 50

Answers (1)

elvira.genkel
elvira.genkel

Reputation: 1333

You go into endless loop because inside the loop you are assigning temp.next, then assign it to current, so current.next is always not 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;

Upvotes: 1

Related Questions