[LeetCode-24] Swap Nodes in Pairs
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.
嗯,注意指针别转乱了就ok~
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 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if (NULL == head) { 15 return NULL; 16 } 17 ListNode *swap1 = head; 18 ListNode *swap2 = head->next; 19 ListNode *swapb = NULL; 20 ListNode *new_head = (NULL == swap2 ? swap1 : swap2); 21 while (NULL != swap1 && NULL != swap2) { 22 if (NULL != swapb) { 23 swapb->next = swap2; 24 } 25 swap1->next = swap2->next; 26 swap2->next = swap1; 27 swapb = swap1; 28 swap1 = swap1->next; 29 if (NULL != swap1) { 30 swap2 = swap1->next; 31 } 32 } 33 return new_head; 34 } 35 };