Skip to content

Commit 3c473ff

Browse files
committed
Added remove nth node from end of a linked-list
1 parent 7f12f2c commit 3c473ff

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# remove nth node from end
2+
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
4+
# brute
5+
# create a new linked list without that element
6+
# Time O(n)
7+
# Space O(n)
8+
9+
# optimal
10+
11+
12+
# Definition for singly-linked list.
13+
class ListNode:
14+
def __init__(self, val=0, next=None):
15+
self.val = val
16+
self.next = next
17+
18+
19+
class Solution:
20+
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
21+
if(head.next == None):
22+
return None
23+
start = ListNode()
24+
start.next = head
25+
slow = fast = start
26+
for i in range(1, n+1):
27+
fast = fast.next
28+
while(fast.next != None):
29+
fast = fast.next
30+
slow = slow.next
31+
slow.next = slow.next.next
32+
return start.next

0 commit comments

Comments
 (0)