leetcode[24]Swap Nodes in Pairs Python3实现(链表节点两两交换,加入虚节点迭代)

该博客讨论了一个链表问题,即如何交换链表中每两个相邻节点。提供了两种解决方案,一种是迭代方法,虽然相对复杂,但能完成任务;另一种是递归算法,更为简洁。所有代码都以Python实现,并附带了示例输入和输出,以及题目约束。
# Given a linked list, swap every two adjacent nodes and return its head. 
# 
#  You may not modify the values in the list's nodes. Only nodes itself may be c
# hanged. 
# 
#  
#  Example 1: 
# 
#  
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
#  
# 
#  Example 2: 
# 
#  
# Input: head = []
# Output: []
#  
# 
#  Example 3: 
# 
#  
# Input: head = [1]
# Output: [1]
#  
# 
#  
#  Constraints: 
# 
#  
#  The number of nodes in the list is in the range [0, 100]. 
#  0 <= Node.val <= 100 
#  
#  Related Topics 链表 
#  👍 680 👎 0

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head: return None
        if not head.next: return head

        pre = head
        post = pre.next
        head = post
        # 虚节点
        lastTail = ListNode(0)
        lastTail.next = pre
        while True:
            pre.next = post.next
            post.next = pre
            lastTail.next = post
            lastTail = pre

            pre = pre.next
            if not pre: break
            post = pre.next
            if not post: break
        return head
# leetcode submit region end(Prohibit modification and deletion)

迭代解法,写的还是麻烦了点,官方题解有递归算法值得学习:

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        newHead = head.next
        head.next = self.swapPairs(newHead.next)
        newHead.next = head
        return newHead
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值