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)
相关推荐
lsswear7 分钟前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
学逆向的13 分钟前
C 循环结构的执行效率分析
c语言·开发语言·数据结构·网络安全
Lhan.zzZ1 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
Data analyse4562 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
sysu_chenxy3 小时前
二重循环输出二维图形
c++
Navigator_Z3 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2084 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年4 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3334 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
jeo陽4 小时前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构