赞
踩
- 输入:head = [1,2,3,4,5]
- 输出:[5,4,3,2,1]
-
- 输入:head = [1,2]
- 输出:[2,1]
-
- 输入:head = []
- 输出:[]
- # 双指针
- # 首先定义一个头指针 pre,然后用当前指针 cur 指向头指针 pre,
- # 循环到 None 停止即可。
- class Solution:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
- pre, cur = None, head
- while cur:
- tmp = cur.next
- cur.next = pre
- pre = cur
- cur = tmp
- return pre
- # 递归
- # 有点难理解了,也就是 head 的下一个节点指向 head,递归结束即可。
- class Solution:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
- if (head == None or head.next == None):
- return head
- cur = self.reverseList(head.next)
- head.next.next = head
- head.next = None
- return cur
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。