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.
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * swappairs (listnode * head) {If (Head = NULL | head-> next = NULL) return head; listnode dummy (0); listnode * tail = & dummy; listnode * pre = head; listnode * cur = NULL; listnode * NXT = NULL; while (pre! = NULL) {cur = pre-> next; If (cur! = NULL) {NXT = cur-> next; cur-> next = pre; pre-> next = NULL; tail-> next = cur; tail = pre; pre = NXT;} else {tail-> next = pre; return dummy. next;} return dummy. next ;}};