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)
相关推荐
√尖尖角↑3 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer3 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
夜月yeyue5 小时前
ARM内核与寄存器
arm开发·stm32·单片机·嵌入式硬件·mcu·链表
百锦再5 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
刚入门的大一新生6 小时前
C++初阶-C++入门基础
开发语言·c++
碳基学AI6 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3647 小时前
每日算法-250410
算法
袖清暮雨7 小时前
Python刷题笔记
笔记·python·算法
weixin_428498497 小时前
Visual Studio 中使用 Clang 作为 C/C++ 编译器时,设置优化选项方法
c语言·c++·visual studio
Marzlam7 小时前
一文读懂数据结构
数据结构