Skip to content

Commit 32d4ab4

Browse files
authored
Merge pull request #139 from WazedKhan/leetcode-19-linked-list
LeetCode #19: Remove Nth Node From End of List
2 parents 64552b3 + cc5a842 commit 32d4ab4

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import Optional
2+
3+
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
10+
class Solution:
11+
def length(self, head: ListNode) -> int:
12+
count = 0
13+
current = head
14+
while current:
15+
count += 1
16+
current = current.next
17+
return count
18+
19+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
20+
n_len = self.length(head=head)
21+
position = n_len - n
22+
dummy = ListNode(0)
23+
dummy.next = head
24+
prev = dummy
25+
26+
for _ in range(position):
27+
prev = prev.next
28+
prev.next = prev.next.next
29+
30+
return dummy.next

0 commit comments

Comments
 (0)