当前位置:   article > 正文

【LeetCode】206. 反转链表 (Python)_力扣反转链表python

力扣反转链表python

作者: 安之若素4869
leetcode主页:https://leetcode-cn.com/u/an-zhi-ruo-su/

题目地址

链接:https://leetcode-cn.com/problems/reverse-linked-list

题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:

输入:head = []
输出:[]

提示:

链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

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

解题思路

递归解法:

[原始] 5 -> 4 ->3->None [结果] —> 3->4->5->None
[self.reverseList(head.next)结果]: 5 3->4->None (此时5还是指向4,只让4指向5,5指向None,返回last即3)

代码

# 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 not head or not head.next:
            return head
        last = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return last     

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

日期

2021-10-07 重新刷codetop高频题,记录思路和易错点,主要是记录多个刷题日期,这样自己知道一道题都在哪几天做过以及熟练程度的变化。模板格式参照复雪明烛大佬。。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/209789
推荐阅读
相关标签
  

闽ICP备14008679号