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;
    }
};
相关推荐
SuperW24 分钟前
数据结构——队列
数据结构
??tobenewyorker1 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
蓝澈11211 小时前
迪杰斯特拉算法之解决单源最短路径问题
java·数据结构
呆瑜nuage3 小时前
数据结构——堆
数据结构
蓝澈11214 小时前
弗洛伊德(Floyd)算法-各个顶点之间的最短路径问题
java·数据结构·动态规划
zl_dfq4 小时前
数据结构 之 【堆】(堆的概念及结构、大根堆的实现、向上调整法、向下调整法)(C语言实现)
数据结构
127_127_1274 小时前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
闪电麦坤954 小时前
数据结构:二维数组(2D Arrays)
数据结构·算法
凌肖战4 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
一定要AK6 小时前
萌新赛练习
数据结构