力扣 24. 两两交换链表中的节点

28 阅读1分钟

🔗 leetcode.cn/problems/sw…

题目

  • RT

思路

  • 递归,每两个节点进行逆序处理

代码

/**
 * 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* find_next_head(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* ans = head->next;
        ListNode* next_head = find_next_head(head->next->next);
        head->next->next = head;
        head->next = next_head;
        return ans;
    }
    ListNode* swapPairs(ListNode* head) {
        return find_next_head(head);
    }
};