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;
    }
};
相关推荐
Sylvia-girl10 小时前
数据结构之复杂度
数据结构·算法
CQ_YM10 小时前
数据结构之队列
c语言·数据结构·算法·
VekiSon11 小时前
数据结构与算法——树和哈希表
数据结构·算法
xu_yule11 小时前
数据结构与算法(1)(第一章复杂度知识点)(大O渐进表示法)
数据结构
fish_xk12 小时前
数据结构之排序
数据结构
Unstoppable2212 小时前
代码随想录算法训练营第 56 天 | 拓扑排序精讲、Dijkstra(朴素版)精讲
java·数据结构·算法·
potato_may12 小时前
CC++ 内存管理 —— 程序的“五脏六腑”在哪里?
c语言·开发语言·数据结构·c++·内存·内存管理
资深web全栈开发14 小时前
LeetCode 3432. 统计元素和差值为偶数的分区方案数
算法·leetcode
ghie909014 小时前
MATLAB自适应子空间辨识工具箱
数据结构·算法·matlab
松涛和鸣15 小时前
25、数据结构:树与二叉树的概念、特性及递归实现
linux·开发语言·网络·数据结构·算法