# [LeetCode 24. Swap Nodes in Pairs] ###### tags: `Leetcode` * 題目 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.) * 解法 * 先新增一個firstNode,目的是要把最後要回傳的存起來 * 之後每兩個一組,進行交換,這邊看程式應該很容易了解 ``` /** /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* swapPairs(struct ListNode* head){ if(!head) return head; struct ListNode* firstNode; struct ListNode* pre; struct ListNode* cur; struct ListNode* next; firstNode=(struct ListNode*) malloc(sizeof(struct ListNode));//建立新節點 firstNode->next = head; pre = firstNode; cur = firstNode->next; while(cur!=NULL && cur->next!=NULL) { next = cur->next->next;//先把下一組的頭頭記起來 pre->next = cur->next;//原本指向cur的變成指向cur->next cur->next->next = cur;//原本指向next的現在指向cur cur->next = next;//cur->next就換成next pre = cur; cur = next; } return firstNode->next; } ```