leetcode 24. 两两交换链表中的节点

题目描述

代码

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(-1,head);
        ListNode *pre = dummyHead;
        ListNode *newHead = nullptr;
        ListNode *post;
        while(pre->next != nullptr && pre->next->next != nullptr){
            ListNode *pair1 = pre->next;
            ListNode *pair2 = pre->next->next;
            if(newHead == nullptr)
                newHead = pair2;
            post = pair2->next;
            pair2->next = pair1;
            pair1->next = post;
            pre->next = pair2;
            pre = pair1;
        }
        delete dummyHead;
        dummyHead = nullptr;
        return newHead;
    }
};
相关推荐
flashlight_hi22 分钟前
LeetCode 分类刷题:2824. 统计和小于目标的下标对数目
javascript·数据结构·算法·leetcode
穆霖祎3 小时前
数据结构(4)
数据结构
秋难降3 小时前
LeetCode——迭代遍历算法
数据结构·算法·排序算法
yanxing.D4 小时前
考研408_数据结构笔记(第四章 串)
数据结构·笔记·考研·算法
冬夜戏雪4 小时前
java学习 leetcode24交换链表节点 200岛屿数量 +一些开发任务
java·学习·链表
এ᭄画画的北北4 小时前
力扣-11.盛最多水的容器
算法·leetcode
啊阿狸不会拉杆5 小时前
《算法导论》第 7 章 - 快速排序
开发语言·数据结构·c++·算法·排序算法
John.Lewis5 小时前
C语言数据结构(4)单链表专题2.单链表的应用
c语言·数据结构·链表
冬夜戏雪5 小时前
java学习 73矩阵置零 54螺旋矩阵 148排序链表
数据结构·算法·矩阵
Dream it possible!6 小时前
LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等)(哈希表)
c++·leetcode·面试·哈希表