LeetCode24 两两交换链表中的节点

前言

题目: 24. 两两交换链表中的节点
文档: 代码随想录------两两交换链表中的节点
编程语言: C++
解题状态: 没画图,被绕进去了...

思路

思路还是挺清晰的,就是简单的模拟,但是一定要搞清楚交换的步骤,绕不清楚的时候最好画图来辅助解决问题。

代码

cpp 复制代码
/**
 * 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) {
        if (head == nullptr || head -> next == nullptr) return head;

        ListNode* dummyHead = new ListNode(0);
        dummyHead -> next = head;
        ListNode* cur = dummyHead;

        while (cur -> next != nullptr && cur -> next -> next != nullptr) {
            ListNode* tmp1 = cur -> next;
            ListNode* tmp2 = cur -> next -> next -> next;

            cur -> next = cur -> next -> next;
            cur -> next -> next = tmp1;
            cur -> next -> next -> next = tmp2;

            cur = cur -> next -> next;
        }

        head = dummyHead -> next;
        delete dummyHead;

        return head;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
相关推荐
感哥15 分钟前
C++ lambda 匿名函数
c++
沐怡旸6 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥7 小时前
C++ 内存管理
c++
聚客AI7 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v9 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工11 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农13 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了13 小时前
AcWing学习——双指针算法
c++·算法
感哥13 小时前
C++ 指针和引用
c++
moonlifesudo14 小时前
322:零钱兑换(三种方法)
算法