I am trying to reverse a linked list pairwise i.e as follows
1->2->3->4->5 changed to 2->1->4->3->5
I have been able to do that recursively. However, I am getting confused while doing it iteratively.
public class FastList<Item>
{
private Node<Item> first;
private static class Node<Item>
{
Item item;
Node<Item> next;
}
public void swapPairwiseIterative() // not working
{
if(first == null || first.next==null)
return;
Node one = first, two;
first= first.next;
while ( one != null || one.next != null )
{
two = one.next;
one.next = two.next;
two.next = one;
one = one.next.next;
}
}
}
On debugging, I noticed that I am able to swap the two nodes correctly, but am not able to assign it back to the first instance variable, which points to the first element of the list. How do I do that ?
Also, the line
first= first.next;
looks a bit hacky. Please suggest a more natural way of doing it.
3->4, how do I change2to point to 4 and not 3 given it is a singly linked list.one = one.next.nextbeone = one.next? since you are swaping one and two, one takes the position of two thus making the start of the next pair be the first node after one, not second