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 class Solution { 2 public ListNode swapPairs(ListNode head) { 3 ListNode fakehead = new ListNode(0); 4 fakehead.next = head; 5 ListNode pre = fakehead; 6 ListNode cur = head; 7 while(cur !=null && cur.next != null){ 8 ListNode next = cur.next; 9 pre.next = next; 10 cur.next = next.next; 11 next.next = cur; 12 pre = cur; 13 cur = pre.next; 14 } 15 return fakehead.next; 16 } 17 }