From c75f6692982472f1f4efd5b957c4d5bb5dbd5985 Mon Sep 17 00:00:00 2001 From: Gabriel Donnan <47415809+gabedonnan@users.noreply.github.com> Date: Tue, 17 Jan 2023 12:59:40 +0000 Subject: [PATCH] Create remove-nth-from-end.py removes the nth element from the end of a linked list. Bad space complexity but fastest method of doing it --- remove-nth-from-end.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 remove-nth-from-end.py diff --git a/remove-nth-from-end.py b/remove-nth-from-end.py new file mode 100644 index 0000000..dc69fb6 --- /dev/null +++ b/remove-nth-from-end.py @@ -0,0 +1,21 @@ +# 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: Optional[ListNode], n: int) -> Optional[ListNode]: + prevList = [head] + found = False + while not found: + if prevList[-1].next != None: + prevList.append(prevList[-1].next) + else: + found = True + if n != 1 and n != len(prevList): + prevList[-(n+1)].next = prevList[-(n-1)] + elif n != len(prevList): + prevList[-(n+1)].next = None + else: + head = head.next + return head