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;
    }
};
相关推荐
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n1 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
努力学算法的蒟蒻1 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495641 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
独好紫罗兰2 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495642 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
我是咸鱼不闲呀2 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
数智工坊2 小时前
【数据结构-树与二叉树】4.5 线索二叉树
数据结构
数智工坊3 小时前
【数据结构-树与二叉树】4.3 二叉树的存储结构
数据结构
独好紫罗兰3 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python