LeetCode.206. 反转链表

本文深入探讨了两种单链表反转的方法,一种利用栈实现,时间复杂度O(N),空间复杂度O(N);另一种采用temp思想,扫描时进行复制,避免空链表问题,为Python最佳解法。

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

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路1:

扫描一遍链表,创建栈保存元素。重建链表,出栈为节点值。

代码1:

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        res=[]
        while head:
            res.append(head.val)
            head=head.next
        m=ListNode(res.pop())
        n=m
        while res:
            m.next=ListNode(res.pop())
            m=m.next
        return n

分析:

时间复杂度O(N),空间复杂度O(N)
此代码击败68%Python提交。

思路2:
temp思想。扫描时进行复制,可同时避免空链表的问题。

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur=None
        pre=None
        while head:
            cur=head
            head=head.next
            cur.next=pre
            pre=cur
        return cur

分析:

此解法为Python最佳。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值