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;
    }
};
相关推荐
仰泳的熊猫11 分钟前
1112 Stucked Keyboard
数据结构·c++·算法·pat考试
he___H43 分钟前
滑动窗口一题
java·数据结构·算法·滑动窗口
AI科技星44 分钟前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
学编程就要猛1 小时前
数据结构初阶:Map和Set接口
数据结构
jianfeng_zhu1 小时前
不带头节点的链式存储实现链栈
数据结构·算法
lightqjx1 小时前
【算法】双指针
c++·算法·leetcode·双指针
历程里程碑1 小时前
C++ 7vector:动态数组的终极指南
java·c语言·开发语言·数据结构·c++·算法
sin_hielo1 小时前
leetcode 2147
数据结构·算法·leetcode
萌>__<新1 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新2 小时前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展