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++ 实现 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

递归版本.

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;
    }
};
发布了455 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104954661