The way I approach this problem is
Draw the
linkedList
for theinput
and desiredoutput
in the right format for the simplest case. Here I would start with 4 nodes;Then tackle the easy cases such as if the
ListNode
or thenext
is nullOn the paper, mark the links that are broken and that are formed. Note you have to do the breaking and linking in right order; Make sure you have
reference
to thenodes
whose link you are breaking. otherwise you might end up losing some nodes. That is the whole crux here. Draw after each step when a node is broken or a link is formed. In this way, you can keep track of what is going;Translate what you have drawn on paper to code. That must be fairly straightforward! Often you would need to have temporary pointers to traverse the list;
In this example, the
front
orhead
pointer needs to be changed. so I would do the first swap outside an iteration. The remaining changes I would inside awhile loop
.write a convienient
toString
method that can help you track the variables at each stage. I found it harder to usedebuggers
forrecusions
andlinkedLists
. but that is just me.
Regarding the solution for this problem: This is not as easy problem in my opinion. but a good one to get a good grasp of linkedLists and
Pointers`
here is my solution:
public void switchPairs(){
if (front==null || front.next==null)
return ;
//keep a pointer to next element of front
ListNode current=front.next;
//make front point to next element
front.next=current.next;
current.next=front;
front=current;
//current has moved one step back it points to first.
//so get it to the finished swap position
current=current.next;
while(current.next!=null && current.next.next!=null){
ListNode temp = current.next.next;
current.next.next=temp.next;
temp.next=current.next;
current.next=temp;
current=temp.next;
}
}