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

题目描述:

题解:

1.创建一个虚拟头节点fakehead,fakehead.next = head。

2.初始时cur = fakehead,每次交换cur.next和cur.next.next两个节点。

3.cur = cur.next.next,继续处理之后的两个节点。

其中cur.next与cur.next.next的交换过程一个示例如下:

此时cur = fakehead,cur.next=1 cur.next.next=2

1.tmp1 = cur.next=1  tmp2=cur.next.next.next=3

2.将fakehead的next指向节点2,通过cur.next = cur.next.next完成。

3. 将节点2的next指向1,即cur.next.next = tmp1

4.将节点1的next指向3,cur.next.next.next=tmp2

以上是对一对相邻节点的处理,然后cur向后移动两个,直到结束。 

class Solution(object):
    def swapPairs(self, head):
        if head == None or head.next == None:
            return head
        fakehead = ListNode(0,head)
        cur = fakehead
        while cur.next and cur.next.next:
            tmp1 = cur.next
            tmp2 = cur.next.next.next
            cur.next = cur.next.next
            cur.next.next = tmp1
            cur.next.next.next = tmp2
            cur = cur.next.next
        return fakehead.next 

2021.11.18

这道题还可以采用递归的思路解决,参考三道题套路解决递归问题 | lyl's blog

把链表分为三个部分:head head.next 已经完成交换的部分

递归终止条件:链表为空或者只有一个节点

当前递归做的工作:将head和head.next交换

返回个下一步的结果:处理完成的链表

class Solution(object):
    def swapPairs(self, head):
        if head==None or head.next==None:
            return head
        next = head.next
        head.next = self.swapPairs(next.next)
        next.next = head
        return next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值