From 3c473ff4e126b2311bc145cb581c63acaf0aca71 Mon Sep 17 00:00:00 2001 From: Om Rawal Date: Fri, 20 Aug 2021 19:09:05 +0530 Subject: [PATCH] Added remove nth node from end of a linked-list --- .../linkedlist/delete_nth_node_from_end.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 algorithms/linkedlist/delete_nth_node_from_end.py diff --git a/algorithms/linkedlist/delete_nth_node_from_end.py b/algorithms/linkedlist/delete_nth_node_from_end.py new file mode 100644 index 0000000..ae77b76 --- /dev/null +++ b/algorithms/linkedlist/delete_nth_node_from_end.py @@ -0,0 +1,32 @@ +# remove nth node from end +# https://leetcode.com/problems/remove-nth-node-from-end-of-list/ + +# brute +# create a new linked list without that element +# Time O(n) +# Space O(n) + +# optimal + + +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + if(head.next == None): + return None + start = ListNode() + start.next = head + slow = fast = start + for i in range(1, n+1): + fast = fast.next + while(fast.next != None): + fast = fast.next + slow = slow.next + slow.next = slow.next.next + return start.next pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy