链表题解——两两交换链表中的节点【LeetCode】

全部题目来自力扣,这里只做学习的记录,内容中部分为AI生成,有不对的地方可以评论或者私信哦~~

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

python 复制代码
# 递归版本

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head

        # 待翻转的两个node分别是pre和cur
        pre = head
        cur = head.next
        next = head.next.next
        
        cur.next = pre  # 交换
        pre.next = self.swapPairs(next) # 将以next为head的后续链表两两交换
         
        return cur

代码执行示例

假设链表为:1 -> 2 -> 3 -> 4 -> None

执行过程:

  1. 第一次递归调用:
    • pre = 1cur = 2next = 3
    • 交换 precur2 -> 1
    • 递归处理 next = 3,得到交换后的链表 4 -> 3
    • pre.next(即 1.next)指向 4 -> 3,最终链表为 2 -> 1 -> 4 -> 3 -> None
    • 返回 cur = 2,即交换后的新链表头节点。

最终链表为:2 -> 1 -> 4 -> 3 -> None

python 复制代码
# Definition for singly-linked list.

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy_head = ListNode(next=head)
        current = dummy_head
        
        # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
        while current.next and current.next.next:
            temp = current.next # 防止节点修改
            temp1 = current.next.next.next
            
            current.next = current.next.next
            current.next.next = temp
            temp.next = temp1
            current = current.next.next
        return dummy_head.next
相关推荐
万粉变现经纪人3 小时前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip
自信的小螺丝钉3 小时前
Leetcode 146. LRU 缓存 哈希表 + 双向链表
leetcode·缓存·散列表
古译汉书4 小时前
嵌入式铁头山羊STM32-各章节详细笔记-查阅传送门
数据结构·笔记·stm32·单片机·嵌入式硬件·个人开发
编程武士4 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao5 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
橘颂TA6 小时前
【数据结构】解锁数据结构:通往高效编程的密钥
数据结构
傻啦嘿哟7 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite
Q_Q5110082857 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
XueminXu7 小时前
Python读取MongoDB的JSON字典和列表对象转为字符串
python·mongodb·json·pymongo·mongoclient·isinstance·json.dumps
techdashen7 小时前
12分钟讲解Python核心理念
开发语言·python