24. Swap Nodes in Pairs**

24. Swap Nodes in Pairs**

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

题目描述

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

C++ 实现 0

(20210402 更新) 迭代版本. 引入虚拟节点, 每次都需要判断 p->next 以及 p->next->next 是否均存在.

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        auto p = dummy;
        while (p->next && p->next->next) {
            auto a = p->next, b = p->next->next;
            auto post = b->next;
            p->next = b;
            b->next = a;
            a->next = post;
            p = a;
        }
        return dummy->next;
    }
};

C++ 实现 1

迭代版本. 引入虚拟节点 dummy 可以简化问题.

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        auto prev = dummy, p = head;
        // 要交换两个节点, 先要判断 ptr 以及 ptr->next 均存在,
      	// 之后用 tmp 记录第三个节点, 也就是下一次交换的开始.
        while (p && p->next) {
            auto tmp = p->next->next;
            prev->next = p->next;
            prev->next->next = p;
            prev = prev->next->next;
            p = tmp;
        }
        prev->next = p; // 不管最后 p 是不是为空, 使用 prev->next 指向它就可以了.
        return dummy->next;
    }
};

C++ 实现 2

20210402 更新. 递归版本; 代码很简洁, C++ 实现 3 写复杂了…, 忍不住更新一下.

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        auto post = head->next->next;
        auto p = head, q = head->next;
        q->next = p;
        p->next = swapPairs(post);
        return q;
    }
};

C++ 实现 3

递归版本.

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next)
            return head;
        
        ListNode *dummy = new ListNode(0);

        auto post = head->next->next;
        dummy->next = head->next;
        dummy->next->next = head;
        dummy->next->next->next = swapPairs(post);
        
        return dummy->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值