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;
    }
};
相关推荐
Darling噜啦啦4 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠5 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾5 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
Qres8215 天前
算法复键——树状数组
数据结构·算法
想吃火锅10055 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
牛油果子哥q5 天前
并查集(DSU)超精讲,路径压缩、按秩合并、万能模板、连通性判定、最小生成树与刷题实战全解
数据结构·c++·最小生成树·并查集
凌波粒5 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
疯狂成瘾者5 天前
Java 集合 LinkedList 详解:链表结构、常用方法和队列使用
java·开发语言·链表
退休倒计时5 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
WL学习笔记5 天前
单项不带头不循环链表
数据结构·链表