Reputation: 61
Infinite loop in a singly linked list reversing algorithm. I tried to do the code on a piece of paper but still can't find the bug
public void reverse ()
{
Node pointer = list;
Node newList = new Node();
Node temp = new Node();
Node tempMoving = new Node();
if (pointer != null)
{
newList = pointer;
while (pointer.next != null)
{
System.out.println ("loop");
temp = pointer;
pointer = pointer.next;
temp.next = pointer.next;
tempMoving = pointer;
tempMoving.next = newList;
newList = tempMoving;
}
}
list = newList;
}
What I envisioned this algorithm to do is that when it moves to a new node, it takes that node and puts it into the beginning of a new list and it will keep repeating until it has reached the end. However, it only prints "loop" :(
Upvotes: 1
Views: 45
Reputation: 79530
You can simply do it as follows:
public void reverse() {
// Assuming `head` is the first node in linked list
Node current = head, previous = null, forward = null;
while (current.next != null) {
forward = current.next;
current.next = previous;
previous = current;
current = forward;
}
head = current;
head.next = previous;
}
Upvotes: 1