Reputation: 11
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
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