当前位置: 首页 > article >正文

LeetCode - 24 两两交换链表中的节点

题目来源

24. 两两交换链表中的节点 - 力扣(LeetCode)

题目描述

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

示例

示例 1:

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

示例 2:

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

示例 3:

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

提示

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

题目解析

本题主要考察数据结构。

对于输入的链表,我们可以为其定义一个虚拟头节点 dummy_head,比如示例1,进行如下逻辑

C源码实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode* dummy_head = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummy_head->val = 0;
    dummy_head->next = head;

    struct ListNode* pre = dummy_head;
    struct ListNode* cur = pre->next;

    while (cur != NULL && cur->next != NULL) { // 由于要交换cur和cur.next两个节点,因此二者不能为null
        struct ListNode* nxt = cur->next;

        cur->next = nxt->next;
        nxt->next = cur;
        pre->next = nxt;

        pre = cur;
        cur = pre->next;
    }

    return dummy_head->next;
}

C++源码实现

/**
 * 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) {
        ListNode* dummy_head = new ListNode(0, head);

        ListNode* pre = dummy_head;
        ListNode* cur = pre->next;

        while (cur != nullptr && cur->next != nullptr) { // 由于要交换cur和cur.next两个节点,因此二者不能为null
            ListNode* nxt = cur->next;

            cur->next = nxt->next;
            nxt->next = cur;
            pre->next = nxt;

            pre = cur;
            cur = pre->next;
        }

        return dummy_head->next;
    }
};

Java源码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy_head = new ListNode(0, head);

        ListNode pre = dummy_head;
        ListNode cur = pre.next;

        while (cur != null && cur.next != null) { // 由于要交换cur和cur.next两个节点,因此二者不能为null
            ListNode nxt = cur.next;

            cur.next = nxt.next;
            nxt.next = cur;
            pre.next = nxt;

            pre = cur;
            cur = pre.next;
        }

        return dummy_head.next;
    }
}

Python源码实现

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        dummy_head = ListNode(0, head)

        pre = dummy_head
        cur = pre.next

        while cur and cur.next:  # 由于要交换cur和cur.next两个节点,因此二者不能为null
            nxt = cur.next

            cur.next = nxt.next
            nxt.next = cur
            pre.next = nxt

            pre = cur
            cur = pre.next
        
        return dummy_head.next
        

JavaScript源码实现

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
    const dummy_head = new ListNode(0, head);

    let pre = dummy_head;
    let cur = pre.next;

    while (cur != null && cur.next != null) { // 由于要交换cur和cur.next两个节点,因此二者不能为null
        const nxt = cur.next;

        cur.next = nxt.next;
        nxt.next = cur;
        pre.next = nxt;

        pre = cur;
        cur = pre.next;
    }

    return dummy_head.next;
};


http://www.kler.cn/a/561516.html

相关文章:

  • 基于JavaWeb开发的高校食堂点餐系统
  • 数据分析七大步骤
  • AIoT安全与隐私自动化建设:实践与展望
  • MYSQL之相关子查询
  • 【教程】使用docker+Dify搭建一个本地知识库
  • 利用Python爬虫获取VIP商品详情:实战案例指南
  • Linux 命名管道
  • Docker 搭建 Nginx 服务器
  • DeepSeek 助力 Vue 开发:打造丝滑的分割线(Divider)
  • 2024年第十五届蓝桥杯青少 图形化编程(Scratch)省赛中级组真题——截取递增数
  • RTSP中RTP/RTCP协议栈、NTP同步及QoS机制
  • Ollama部署本地大模型DeepSeek-R1-Distill-Llama-70B
  • 如何成为Apache Doris的贡献者
  • Windows 中的启动项如何打开?管理电脑启动程序的三种方法
  • 13. MySQL 事务基础知识(详细说明实操剖析)
  • C++编程指南17 - 使用 RAII(资源获取即初始化),避免直接调用 lock()/unlock()
  • 医疗UI的特殊法则:复杂数据可视化的“零错误”设计守则
  • DeepSeek赋能机器人革命:从推理引擎到行业落地的全栈技术实践
  • #Oracle 学习进阶路线-进阶篇:高可用、性能调优与云原生的实战突破
  • el-select滚动获取下拉数据;el-select滚动加载