Leetcode24. 两两交换链表中的节点 -hot100-代码随想录-春招冲刺

文章介绍了如何使用单指针和双指针方法解决链表中每两个节点交换的问题,逐步优化代码,最终实现无bug的解决方案。
摘要由CSDN通过智能技术生成

题目:


代码(首刷看解析 2024年1月12日):

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==nullptr) return nullptr;
        ListNode* cur = new ListNode(0,head);
        ListNode* dummy = cur;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp = cur->next;
            ListNode* tmp2 = cur->next->next->next;

            cur->next = cur->next->next;
            cur->next->next = tmp;
            tmp->next = tmp2;

            cur = cur->next->next;
        } 
        return dummy->next;
    }
};

        链表类题目一定要画图


代码(二刷看思路 2024年3月4日)

        有时候图画对了,代码不一定写的对,这题单指针要比双指针简单

/**
 * 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* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0, head);
        ListNode* cur = dummyHead;
        while (cur->next && cur->next->next) {
            ListNode* N1 = cur->next;
            ListNode* N2 = cur->next->next;

            // 变换
            cur->next = N2;
            N1->next = N2->next;
            N2->next = N1;

            cur = cur->next->next;
        }
        return dummyHead->next;
    }
};

代码(三刷自解 2024年4月11日)

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0, head);
        ListNode* cur = dummyHead;
        ListNode* left;
        ListNode* right;
        while (cur->next && cur->next->next) {
            left = cur->next;
            right = cur->next->next;
            // 开始变向
            left->next = right->next;
            cur->next = right;
            right->next = left;
            cur = left;
        }
        return dummyHead->next;
    }
};

代码(四刷自解 2024年4月16日 BUGFREE)

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        // 每次交换,获得交换前的节点
        ListNode* dummy = new ListNode(0, head);
        ListNode* cur = dummy;
        while (cur->next && cur->next->next) {
            // 交换
            ListNode* N1 = cur->next;
            ListNode* N2 = N1->next;
            N1->next = N2->next;
            cur->next = N2;
            N2->next = N1;
            //更新cur
            cur = N1; 
        }
        return dummy->next;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值