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;
    }
};
相关推荐
墨染点香4 小时前
LeetCode 刷题【126. 单词接龙 II】
算法·leetcode·职场和发展
aloha_7895 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode
Tiny番茄5 小时前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的5 小时前
最长连续序列
数据结构·c++·算法
_Aaron___5 小时前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
码农多耕地呗7 小时前
力扣146.LRU缓存(哈希表缓存.映射+双向链表数据结构手搓.维护使用状况顺序)(java)
数据结构·leetcode·缓存
晚枫~7 小时前
数据结构基石:从线性表到树形世界的探索
数据结构
hadage2338 小时前
--- 数据结构 AVL树 ---
数据结构·算法
liu****8 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛8 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生