LeetCode24. 两两交换链表中的节点

24. 两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

img

输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100

代码

class Solution {
   
public:
    ListNode* swapPairs(ListNode* head) {
   
        ListNode* dummyNode = new ListNode(-1);
        dummyNode->next = head;
        ListNode* cur = dummyNode;
        while (cur->next != NULL && cur->next->next != NULL) {
   
            ListNode* temp1 = cur->next;
            cur->next = temp1->next;
            ListNode* temp2 = cur->next->next;
            cur->next->next = temp1;
            cur->next->next->next = temp2;
            cur = cur->next->next;
        }
        return dummyNode->next;
    }
};

image-20240129222233013

相关推荐

  1. leetcode24. 交换节点

    2024-01-30 19:42:02       66 阅读
  2. LeetCode [24] 交换节点

    2024-01-30 19:42:02       67 阅读
  3. Leetcode24. 交换节点

    2024-01-30 19:42:02       64 阅读
  4. LeetCode24.交换节点

    2024-01-30 19:42:02       66 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-30 19:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-30 19:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-30 19:42:02       82 阅读
  4. Python语言-面向对象

    2024-01-30 19:42:02       91 阅读

热门阅读

  1. 【城市大脑】城市数字大脑:智慧城市的新引擎

    2024-01-30 19:42:02       49 阅读
  2. 5.llama.cpp编译及使用

    2024-01-30 19:42:02       55 阅读
  3. 力扣0108——将有序数组转换为二叉搜索树

    2024-01-30 19:42:02       68 阅读
  4. 01_02_mysql02_DDL

    2024-01-30 19:42:02       66 阅读
  5. 力扣0110——平衡二叉树

    2024-01-30 19:42:02       65 阅读
  6. 迷宫(蓝桥杯省赛C/C++)

    2024-01-30 19:42:02       57 阅读
  7. python中yield的用法

    2024-01-30 19:42:02       62 阅读
  8. 龙哥风向标 20230321~20230328 GPT拆解

    2024-01-30 19:42:02       43 阅读