LeetCode24两两交换链表中的节点

题目链接

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

题解

  • 递归解法,我自己写的
  • 要明确函数的功能
  • 函数中需手动处理空链表和链表中只有1个节点的情况;多个节点时,先手动交换前两个节点,然后通过递归交换其它节点
// Problem: LeetCode 24
// URL: https://leetcode-cn.com/problems/swap-nodes-in-pairs/
// Tags: Linked List Recursion
// Difficulty: Medium

#include <iostream>
using namespace std;

struct ListNode{
    int val;
    ListNode* next;
};

class Solution{
public:
    ListNode* swapPairs(ListNode* head) {
        // 空链表或只有1个节点
        if (head==nullptr || head->next==nullptr) return head;
        // 取第2和3个节点
        ListNode *newHead=head->next, *subHead = head->next->next;
        // 交换第1个节点和第2个节点,递归交换其它节点并进行连接
        newHead->next = head;
        head->next = swapPairs(subHead);
        return newHead;
    }
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


猜你喜欢

转载自www.cnblogs.com/chouxianyu/p/13406395.html