24. Swap Nodes in Pairs [easy] (Python)

本博客介绍了LeetCode中的一道题目——交换链表中的相邻节点,要求在O(1)空间复杂度下完成。文章提供了两种Python解题思路,思路一是以两个节点为单位进行交换,思路二是通过构造新链表来实现相邻节点的逆序插入。文章最后邀请读者指出错误并标明转载来源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://leetcode.com/problems/swap-nodes-in-pairs/

题目原文

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目翻译

给定一个单链表,交换相邻的节点,并返回链表头。比如,给定1->2->3->4,你应该返回 2->1->4->3。
注意:你的算法应该是O(1)的空间复杂度,不能修改链表节点的值(val),只能修改节点。

思路方法

思路一

既然每次交换相邻节点,那么就以两个节点为一个单位做处理,循环每次交换两个相邻节点即可。

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        pre = new_head = ListNode(0)
        while head and head.next:
            tmp = head.next
            head.next = tmp.next
            tmp.next = head
            pre.next = tmp
            pre = head
            head = head.next
        return new_head.next

说明
上面的思路,可以换个角度考虑:现在是用现在的节点构造一个新的链表,每次向新链表添加两个节点,这两个节点是原链表的相邻节点的逆序。

思路二

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        new_head = head.next
        head.next = self.swapPairs(head.next.next)
        new_head.next = head
        return new_head

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51532184

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值