Reputation: 5384
I'm studying data structure in Java.
I have a linked list:
1 -> 2 -> 3 -> 4 -> 5
And I'd like to reverse the linked list, but in a pair.
2 -> 1 -> 4 -> 3 -> 5
I wrote a code, but it doesn't work
private void reversePair(Node headNode) {
Node tempNode1 = null;
Node tempNode2 = null;
Node currentNode = headNode;
while(currentNode != null && currentNode.getNext() != null) {
tempNode1 = currentNode.getNext();
tempNode2 = tempNode1.getNext();
tempNode1.setNext(currentNode);
currentNode.setNext(tempNode2);
currentNode = currentNode.getNext();
}
}
It became 1 -> 3 -> 5
, and I don't know what's the logic hole here.
Could you explain what's the problem in my code and the solution?
Upvotes: 0
Views: 278
Reputation: 63
You have two problem inside your code. The first one is that the node that you pass to the method doesn't change outside the method, it still point to 1! The second problem is inside the while loop... you do something like
temp1->2, temp2->3 after that 2->1 and 1->3 at the end of the while you obtain
2->1->3->4->.... that is ok But now:
1) as I said headNode, outside the method, point to 1, so it see the list as 1->3->4->...
2) the next while iteration swap 3 and 4 (4->3,3->5), but 1 still point to 3, it doesn't change! So the headNode outside the method see the list as 1->3->5->...
Fixing the second problem should be easy. The first one is more difficult, I suggest to save 2 ( the new head) and return it as the new head. It's not elegant, you have to call the method as headNode = reversePair(headNode)
but it should work.
Upvotes: 1