目录

欢乐力扣反转链表

欢乐力扣:反转链表


1、题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

https://i-blog.csdnimg.cn/direct/e634b45cb4bb48e5b57bb88aae3922ae.png

2、思路

借助cur指针和pre双指针来调整链表的前后指向。

# 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