链表题解——两两交换链表中的节点【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
相关推荐
j_xxx404_11 分钟前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
南莺莺15 分钟前
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判别,表达式中的括号是否配对,以字符“\0“作为算术表达式的结束符
c语言·数据结构·算法·
nuclear201116 分钟前
Python 实现 Markdown 与 Word 高保真互转(含批量转换)
python·word转markdown·markdown转word·word转md·md转word
山烛18 分钟前
深度学习:CNN 模型训练中的学习率调整(基于 PyTorch)
人工智能·pytorch·python·深度学习·cnn·调整学习率
Lris-KK23 分钟前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
THMAIL32 分钟前
深度学习从入门到精通 - 神经网络核心原理:从生物神经元到数学模型蜕变
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
珍珠是蚌的眼泪35 分钟前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦37 分钟前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode
墨染点香40 分钟前
LeetCode 刷题【61. 旋转链表】
算法·leetcode·职场和发展