# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
tmp = cur.next # tmp用于保存后继节点 cur.next,防止丢失
cur.next = pre # 修改 next 引用指向,让其指向null
pre = cur # pre 暂存 cur
cur = tmp # cur 访问下一节点。让第二个节点作为头节点
return pre
#时间/空间复杂度都是O(n)
python反转链表
最新推荐文章于 2024-07-13 23:51:10 发布