力扣刷题Day 25:反转链表(206)
1.题目描述
2.思路
递归。
3.代码(Python3)
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:def helper(node):if node.next.next is not None:helper(node.next)else:nonlocal headhead = node.nextnode.next.next = nodereturn nodeif head is None:return Noneelif head.next is None:return headhead_node = headhelper(head_node).next = Nonereturn head
4.执行情况
5.感想
又在题解里看到了更简便的迭代算法,如下:
class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:cur.next, pre, cur = pre, cur, cur.nextreturn pre作者:Krahets
链接:https://leetcode.cn/problems/reverse-linked-list/solutions/2361282/206-fan-zhuan-lian-biao-shuang-zhi-zhen-r1jel/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。