Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, You shoshould return the list2->1->4->3
.
Your algorithm shocould use only constant space. You mayNotModify the values in the list, only nodes itself can be changed.
Set the head node for easy operation and reverse each two
1/** 2 * definition for singly-linked list. 3 * struct listnode {4 * int val; 5 * listnode * Next; 6 * listnode (int x): Val (x), next (null) {} 7 *}; 8 */9 class solution {10 public: 11 listnode * swappairs (listnode * head) {12 if (! Head) return head; 13 listnode node (-1); // set the header node 14 node. next = head; 15 listnode * pre = & node; 16 listnode * P = head; 17 while (P & P-> next) {// if the current node and the next node have 18 pre-> next = p-> next; 19 P-> next = p-> next; 20 pre-> next = P; 21 pre = P; 22 p = p-> next; 23} 24 return node. next; 25} 26 };
Swap nodes in pairs