# 【LeetCode】 24. Swap Nodes in Pairs ## Description > Given a linked list, swap every two adjacent nodes and return its head. > You may not modify the values in the list's nodes, only nodes itself may be changed. > 給一個linked list,每兩個節點就交換一次,並回傳整個linked list的頭。 > 你不該修改節點的值,你應該直接對節點做交換。 ## Example: ``` Example: Given 1->2->3->4, you should return the list as 2->1->4->3. ``` ## Solution * 把第二個指向第一個,再把第一個指向第四個。 * 如果第四個是`NULL`,則指向第三個,然後直接結束。 * 把第一個更新為第三個。 * 如果第三個是`NULL`,直接結束。 * 記得把開頭的head更新成第二個。 * 如果只有一個節點或根本沒有節點,直接回傳head。 ### Code ```C++=1 class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* temp = head; if(head && head->next) { head = head->next; while (temp&&temp->next) { ListNode* n = temp->next->next; temp->next->next = temp; if (n) { if (n->next) { temp->next = n->next; temp = n; } else { temp->next = n; n->next = NULL; break; } } else { temp->next = NULL; break; } } } return head; } }; ``` ###### tags: `LeetCode` `C++`