来自北大算法课的Leetcode题解:206. 反转链表

本文详细介绍了两种常见的链表翻转方法:递归解法和迭代解法。递归解法通过将链表后半部分视为一个节点进行翻转,而迭代解法则使用一个新的链表来构建翻转后的结果。文中提供了具体的Python实现,并对代码进行了优化,使得链表翻转的过程更加简洁高效。这两种方法对于理解和操作链表具有重要的实践意义。

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

  • 解法1(T73% S17%): 递归,把当前head后面的所有东西看成一个节点,newHead=递归后面的东西,当前的head要作为最后一个节点,所以head.next.next = head,这里的两个next就相当于把后面的东西都当成一个节点了,递归终止条件是head或head.next为空

    if head is None or head.next is None:
        return head
    newHead = self.reverseList(head.next)
    head.next.next = head
    head.next = None
    return newHead
    
  • 解法2(T42% S72%): 建立一个新链表,依次循环原链表,在新链表头不断插入

    • 改进(T90% S45%):利用python独特的语法,把整个链接过程在一行写完
    dummy = ListNode(next=None)
    while head:
        dummy.next, head.next, head = head, dummy.next, head.next
    return dummy.next
    
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 解法2 改进
        dummy = ListNode(next=None)
        while head:
            dummy.next, head.next, head = head, dummy.next, head.next
        return dummy.next


    def otherSolution(self, head):
        # 解法1 递归
        if head is None or head.next is None:
            return head
        newHead = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return newHead

        # 解法2 循环
        result = None
        while head:
            save = head
            head = head.next
            save.next = result
            result = save
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

doubleZ0108

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

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

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

打赏作者

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

抵扣说明:

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

余额充值