Skip to content

Commit

Permalink
Create remove-nth-from-end.py
Browse files Browse the repository at this point in the history
removes the nth element from the end of a linked list. Bad space complexity but fastest method of doing it
  • Loading branch information
gabedonnan authored Jan 17, 2023
1 parent 300c124 commit c75f669
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions remove-nth-from-end.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit c75f669

Please sign in to comment.