【剑指 Offer-简单】剑指 Offer 24. 反转链表

本文介绍了四种不同的Python方法来翻转链表,包括使用栈的非原地方法、原地翻转、递归法以及递归解法。每种方法都详细解释了执行过程,并给出了执行时间和内存消耗,适合学习链表操作和算法优化。

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

题目
代码
执行用时:36 ms, 在所有 Python3 提交中击败了72.30% 的用户
内存消耗:16.1 MB, 在所有 Python3 提交中击败了34.25% 的用户
通过测试用例:27 / 27

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        stack=[]
        while head:
            stack.append(head)
            head=head.next
        if not stack:
            return None
        ans=stack[-1]
        now=ans
        stack.pop()
        while stack:
            temp=stack.pop()
            now.next=temp
            now=temp
        now.next=None
        return ans   

【方法2:原地,不占用额外空间】
执行用时:40 ms, 在所有 Python3 提交中击败了46.78% 的用户
内存消耗:16.1 MB, 在所有 Python3 提交中击败了36.94% 的用户
通过测试用例:27 / 27

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None:
            return None
        pre,now=head,head
        while now:
            if now==pre:
                now=now.next
            else:
                temp_now=now
                temp_now_next=now.next
                now.next=pre
                pre=temp_now
                now=temp_now_next
        head.next=None
        return pre

【方法3:递归法】
执行用时:52 ms, 在所有 Python3 提交中击败了9.41% 的用户
内存消耗:20.6 MB, 在所有 Python3 提交中击败了10.97% 的用户
通过测试用例:27 / 27

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        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

【方法4:递归】

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def recur(cur, pre):
            if not cur: return pre     # 终止条件
            res = recur(cur.next, cur) # 递归后继节点
            cur.next = pre             # 修改节点引用指向
            return res                 # 返回反转链表的头节点
        
        return recur(head, None)       # 调用递归并返回
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值