文章目录
1、题目描述
反转链表。
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

2、思路
借助cur指针和pre双指针来调整链表的前后指向。
python
# 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: Optional[ListNode]) -> Optional[ListNode]:
# 反转链表
cur = head
pre = None
while cur:
tmp = cur.next # step2: 考虑到先存储后续节点
cur.next = pre # step1: 关键:修改指向
pre = cur # step3: 在cur变更之前,你得先调整pre的节点
cur = tmp # step4: 将tmp更新cur节点
return pre # 此时cur已经指向了None