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;
    }
};
相关推荐
黄皮の电气鼠41 分钟前
链表——C语言
c语言·数据结构·链表
半桔1 小时前
定长滑动窗口---初阶篇
数据结构·c++·算法·leetcode·面试
dot to one1 小时前
C++ set和map系列(关联式容器)的介绍及使用
开发语言·数据结构·c++·visual studio·红黑树
bai_lan_ya2 小时前
数据结构之栈与队列
数据结构
元亓亓亓3 小时前
LeetCode热题100--73.矩阵置零--中等
算法·leetcode·矩阵
末央&4 小时前
【数据结构】手撕二叉搜索树
开发语言·数据结构·c++
珹洺4 小时前
C++从入门到实战(十二)详细讲解C++如何实现内存管理
c语言·开发语言·数据结构·c++
悦悦子a啊5 小时前
第八章--图
数据结构·c++·算法
东方芷兰5 小时前
Leetcode 刷题记录 09 —— 链表第三弹
算法·leetcode·链表
星夜9825 小时前
C++回顾 Day4
开发语言·数据结构·c++