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)
相关推荐
VT.馒头5 分钟前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
小镇敲码人9 分钟前
剖析CANN框架中Samples仓库:从示例到实战的AI开发指南
c++·人工智能·python·华为·acl·cann
刘琦沛在进步42 分钟前
【C / C++】引用和函数重载的介绍
c语言·开发语言·c++
我在人间贩卖青春1 小时前
C++之this指针
c++·this
爱敲代码的TOM1 小时前
数据结构总结
数据结构
云姜.1 小时前
java多态
java·开发语言·c++
CoderCodingNo2 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳10302 小时前
C++:红黑树
开发语言·c++
大闲在人2 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
一切尽在,你来2 小时前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++