给你单链表的头节点 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
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 链表反转,需要知道当前指针和前一个指针
prev = None
curr = head
while curr:
# 当把curr.next指针断开,指向prev时,需要一个临时指针记录当前curr.next的指向,否则改变前curr.next的指向会断开,丢失
next = curr.next
# 要遍历,需要断开移动指针curr.next当前一个节点pre
curr.next = prev
# 遍历,prev指针优先指向当前指针
prev = curr
curr = next
return prev