来自北大算法课的Leetcode题解:24. 两两交换链表中的节点

代码仓库Github | Leetcode solutions @doubleZ0108 from Peking University.

处理链表问题的核心是要记住之前一段的末尾和接下来一段的起点,推荐直接用pre和last两个变量来存,每次更新,不要想着用一个变量move就能搞定

  • 解法1(T94% S55%): 首先设置头节点存储空位,接下来设置好pre和last,在纸上想好连接的顺序,①move.next.next连到move上(交换顺序) ②pre.next连到move.next上(把之前的串上) ③pre更新 ④move.next指向last ⑤更新move循环下一截

    image.png

  • 解法2(T76% S72%): 利用python特殊的语法,我们的目的是

    p r e → a → b → b . n e x t ⇒ p r e → b → a → b . n e x t pre \rightarrow a \rightarrow b \rightarrow b.next \Rightarrow pre \rightarrow b \rightarrow a \rightarrow b.next preabb.nextprebab.next

    直接看我们要得到的链,通过python语法可以直接写

    pre.next, b.next, a.next = b, a, b.next
    

    其他就是记得初始化以及更新pre了,由于最前头也需要pre,所以也需要加一个头指针,可以如下简易实现

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

    def __repr__(self) -> str:
        return "{} -> {}".format(self.val, repr(self.next))

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre, pre.next = self, head
        while pre.next and pre.next.next:
            a, b = pre.next, pre.next.next
            pre.next, b.next, a.next = b, a, b.next
            pre = a
        return self.next
        
    def otherSolution(self):
        if not head or not head.next:   # 空 or 只有一个节点
            return head

        result = ListNode()
        result.next = head

        pre = result
        move = head
        while move and move.next:
            last = move.next.next
            move.next.next = move
            pre.next = move.next
            pre = move
            move.next = last
            move = last
        
        return result.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

doubleZ0108

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值