LeetCode 206 Reverse Linked List (Python)

Posted by 小明MaxMing on March 16, 2022

题目

Given the head of a singly linked list, reverse the list, and return the reversed list.

解题思路

递归和非递归两种方法

代码

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return p
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head
        while cur:
            t = cur.next
            cur.next = pre
            pre = cur
            cur = t
        return pre

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅