ZhongKuo0228 / study

0 stars 0 forks source link

24. Swap Nodes in Pairs #54

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

https://leetcode.com/problems/swap-nodes-in-pairs/description/

fockspaces commented 1 year ago

有點驚訝一次就過了,而且還比之前的效率好

這題用 recursion,先往最深處 swap,接著慢慢串回來 注意 base case:遇到 tail node (odd) or NULL (even),直接 return 當前 node 之後不斷 swap 即可

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* next = head->next;
        head->next = swapPairs(next->next);
        next->next = head; head = next;
        return head;
    }
};