--- title: 'LeetCode 24. Swap Nodes in Pairs' disqus: hackmd --- # LeetCode 24. Swap Nodes in Pairs ## Description Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) ## Example Input: head = [1,2,3,4] Output: [2,1,4,3] Input: head = [ ] Output: [ ] ## Constraints The number of nodes in the list is in the range [0, 100]. 0 <= Node.val <= 100 ## Answer 兩兩做SWAP,先做一個SWAP拿出開頭,然後進入while,因為SWAP後還要接上原項目,所以是給head->next去做SWAP,然後head->next接上之後就可以往下推進了。 ```Cin= struct ListNode* SWAP(struct ListNode* nod){ if(nod->next == NULL){return nod;} struct ListNode *nxt = nod->next; nod->next = nxt->next; nxt->next = nod; return nxt; } // 2022_05_02 struct ListNode* swapPairs(struct ListNode* head){ if(head == NULL || head->next == NULL){return head;} struct ListNode *ans = NULL, *tmp = NULL; ans = SWAP(head); while(head != NULL && head->next != NULL){ tmp = SWAP(head->next); head->next = tmp; head = head->next->next; } return ans; } ``` ## Link https://leetcode.com/problems/swap-nodes-in-pairs/ ###### tags: `Leetcode`