赞
踩
作者: 安之若素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
2021-10-07 重新刷codetop高频题,记录思路和易错点,主要是记录多个刷题日期,这样自己知道一道题都在哪几天做过以及熟练程度的变化。模板格式参照复雪明烛大佬。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。