LeetCode:206. 反转链表(python)

LeetCode:206. 反转链表(python)

反转一个单链表。

示例:

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

进阶:你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

LeetCode 链接

思路

  • 迭代
    • 记录 pre,cur,nex 指针进行翻转链表方向和迭代
  • 递归
    • 见代码注释
附代码(Python):
  • 迭代

    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    # pre,cur,nex 指针迭代
    class Solution:
        def reverseList(self, head):
            if not head:
                return None
            pre, cur = None, head
            while cur.next:
                nex = cur.next
                cur.next = pre
                pre = cur
                cur = nex
            cur.next = pre
            return cur        
    
    # 构建链表
    head = cur = ListNode(None)
    for i in [1, 2, 3, 4, 5]:
        cur.next = ListNode(i)
        cur = cur.next
    head = head.next
    
    # 反转链表
    test = Solution()
    res = test.reverseList(head)
    while res:
        print(res.val, end=' ')
        res = res.next
    
    5 4 3 2 1
    
  • 递归

    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    # 递归
    class Solution:
        def reverseList(self, head):
            if head == None or head.next == None:   # head==None 是为了防止传入的 head 为空;head.next==None 为递归的返回条件
                return head
            cur = self.reverseList(head.next)         # cur 第一次返回为链表尾端,即反转链表的头部,且将不断返回,不再更改
            head.next.next = head                     # head 此时为前一节点,改变链表指向
            head.next = None                         # 将新的尾节点指向 None,该尾节点不断更新
            return cur
    
    # 构建链表
    head = cur = ListNode(None)
    for i in [1, 2, 3, 4, 5]:
        cur.next = ListNode(i)
        cur = cur.next
    head = head.next
    
    # 反转链表
    test = Solution()
    res = test.reverseList(head)
    while res:
        print(res.val, end=' ')
        res = res.next
    
    5 4 3 2 1 
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值