0

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

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.