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.
1 public class Solution { 2 public ListNode swapPairs(ListNode head) { 3 if(head==null ||head.next==null) return head; 4 ListNode safe = new ListNode(-1); 5 ListNode post = safe; 6 ListNode cur = head; 7 ListNode pre = head.next; 8 while(pre!=null){ 9 ListNode temp = pre.next; 10 pre.next = cur; 11 cur.next = temp; 12 post.next = pre; 13 post = cur; 14 if(post.next!=null){ 15 cur = post.next; 16 pre = cur.next; 17 } 18 else break; 19 } 20 return safe.next; 21 } 22 }