Given a linked list, swap every, adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Problem Solving Ideas:
You need to use Fakehead to point to the original pointer, to prevent the chain, with two pointers, thepre always points to the pair that needs to be exchanged before a node,cur always points to the first node of the pair that needs to be exchanged.
Then just make a normal list exchange, and the pointer moves just fine.
When the list length is odd, the cur.next may be null;
Cur may be null when the list length is even.
So the two conditions as the termination condition, in the while judgment is good, and finally return to Fakehead.next.
Linked list Exchange I don't understand, I need someone to help me to tell.
Java Code:
Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL){ returnHead; } ListNode Fakehead=NewListNode (0); Fakehead.next=Head; ListNode Pre=Fakehead; ListNode cur=Head; while(cur!=NULL&& Cur.next! =NULL) {Pre.next=Cur.next; Cur.next=Cur.next.next; Pre.next.next=cur; Pre=cur; Cur=Cur.next; } returnFakehead.next; }}
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html
2. http://www.cnblogs.com/springfor/p/3862030.html
Leetcode Swap Nodes in Pairs