-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
removes the nth element from the end of a linked list. Bad space complexity but fastest method of doing it
- Loading branch information
1 parent
300c124
commit c75f669
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |