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/

欢迎讨论和交流!


posted @ 2020-07-30 21:19  臭咸鱼  阅读(75)  评论(0编辑  收藏  举报