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;
    }
};
相关推荐
努力努力再努力wz34 分钟前
【MySQL进阶系列】拒绝冗余SQL:带你透彻理解视图的底层逻辑
android·c语言·数据结构·数据库·c++·sql·mysql
m0_629494731 小时前
LeetCode 热题 100-----18.矩阵置零
数据结构·leetcode·矩阵
阿Y加油吧2 小时前
二刷 LeetCode:两道经典贪心题复盘
算法·leetcode·职场和发展
Java成神之路-2 小时前
【LeetCode 刷题笔记】35. 搜索插入位置 | 二分查找经典入门题
算法·leetcode
SunnyByte2 小时前
数据结构——算法效率
数据结构
Navigator_Z12 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
jiushiapwojdap14 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
纽扣66715 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
xvhao201318 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
We་ct18 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划