给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
输入:
head = [1,2,3,4,5]
输出:
[5,4,3,2,1]
很多初学者会误解输入 head = [1,2,3]
是 Python 列表。其实这是题目的简化表示方式,真正传入 reverseList
函数的是链表结构,如下:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
链表在内存中的结构类似这样:
ListNode(1) → ListNode(2) → ListNode(3) → None
反转链表的本质是:逐步改变每个节点的 next
指针方向。
指针 | 含义 |
---|---|
cur | 当前正在处理的节点 |
pre | 当前节点的前一个节点(反转部分的头) |
tmp | 临时保存 cur.next,防止链断 |
以链表 1 → 2 → 3 → None
为例:
pre = None
cur = 1
tmp = cur.next # tmp = 2
cur.next = pre # 1 → None
pre = cur # pre = 1
cur = tmp # cur = 2
tmp = 3
2 → 1 → None
pre = 2
cur = 3
tmp = None
3 → 2 → 1 → None
cur = None,结束
最终返回 pre
,即新的头节点。
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from typing import Optional
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
while cur:
tmp = cur.next # 1. 暂存下一个节点
cur.next = pre # 2. 当前节点指向前一个
pre = cur # 3. pre 向前移动
cur = tmp # 4. cur 向前移动
return pre
错误描述 | 原因 |
---|---|
cur.next = cur | 会造成死循环,指针指向自己 |
忘记保存 cur.next | 链表断链,后面访问不到 |
最后返回 cur | cur 最后是 None,应返回 pre |
虽然迭代更推荐,但你也可以使用递归反转链表:
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有