反转链表

last modify

206. 反转链表 - 力扣(LeetCode)

问题简述

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

思路

  • 定义 pre, cur, nxt 三个指针, 详见代码;

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]:

        pre, cur = None, head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt

        return pre

Last updated