Swap Nodes in Pairs
Given a linked list, swap every two 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. You may not modify the values in the list, only nodes itself can be changed.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ListNode swapPairs(ListNode head) { 3 ListNode safe = new ListNode(-1); 4 ListNode pre = safe; 5 safe.next = head; 6 ListNode cur = head; 7 if(head==null || head.next==null) return head; 8 ListNode post = head.next; 9 while(post!=null){ 10 ListNode temp = post.next; 11 post.next = cur; 12 cur.next = temp; 13 pre.next = post; 14 pre = cur; 15 cur = temp; 16 post = temp==null?null:temp.next; 17 } 18 return safe.next; 19 } 20 }