NYUer | LeetCode19 Remove Nth Node From End of List

LeetCode19 Remove Nth Node From End of List


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

Description Medium

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1

在这里插入图片描述

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2
Input: head = [1], n = 1
Output: []
Example 3
Input: head = [1,2], n = 1
Output: [1]
Constrains
  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Analysis

We use two pointers to solve this problem. The fast pointer moves first, the range is n+1. And then, slow and fast pointers move together until fast pointer is None. At this time, slow pointer is at the previous node of that node which should be removed. Use slow.next = slow.next.next to remove the node. The most important thought in this problem is move fast pointer n+1 steps.

Solution

  • Two pointers 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 removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy_head = ListNode(0)
        dummy_head.next = head
        fast = slow = dummy_head

        for _ in range(n + 1):  # key condition
            fast = fast.next
        
        while fast != None:
            fast = fast.next
            slow = slow.next
        
        slow.next = slow.next.next

        return dummy_head.next

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值