NYUer | LeetCode206 Reverse Linked List

该博客围绕LeetCode206反转单链表问题展开。介绍了问题描述、示例及约束条件,分析中提出用两个索引操作节点实现反转,给出双索引解法,还提到链表反转可迭代或递归实现,并给出递归版本,希望能为解题提供启发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode206 Reverse Linked List


Author: Stefan Su
Create time: 2022-10-28 00:49:07
Location: New York City, NY, USA

Description Easy

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

Example 1

在这里插入图片描述

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2

在这里插入图片描述

Input: head = [1,2]
Output: [2,1]
Example 3
Input: head = []
Output: []
Constrains
  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Analysis

Use two indices, cur and prev to indicate the two nodes to be operated. In each while loop, use temp variable to store cur.next first. And then, set cur.next to prev to complete reverse. Finally, update prev to cur and cur to temp. Attention, the order is really important here. We stop while loop until cur pointer points to a null pointer.

Solution

  • Two indices version.
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        # Two index version
        cur = head
        prev = None

        while cur != None:
            temp = cur.next
            cur.next = prev
            prev = cur
            cur = temp
        
        return prev

Advance

A linked list can be reversed either iteratively or recursively.

  • Recursion version
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # recursion version
        def reverse(cur, prev):
            if cur == None:
                return prev

            temp = cur.next
            cur.next = prev
            return reverse(temp, cur)

        return reverse(head, None)

    # can also write the reserve function outside of reserveList, but add self to call it
    # def reverse(self, cur, prev):
    #     if cur == None:
    #         return prev

    #     temp = cur.next
    #     cur.next = prev
    #     return self.reverse(temp, cur)

Hopefully, this blog can inspire you when solving LeetCode206. For any questions, please comment below.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值