Press "Enter" to skip to content

花花酱 LeetCode 19. Remove Nth Node From End of List

Problem

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

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Solution 0: Cheating! store the nodes in an array

C++

Solution 1: Two passes

Time complexity: O(L)

Space complexity: O(1)

C++

Solution 2: Fast/Slow Pointers + Dummy Head / Prev

Fast pointer moves n steps first, and then slow pointer starts moving.

When fast pointer reaches tail, slow pointer is n-th node from the end.

Time complexity: O(L)

Space complexity: O(1)

C++

Java

Python3

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply