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
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: