Skip to content

Commit a22814e

Browse files
committed
Adding Efficient Solution for Problem - 19 - Remove Nth Node From End
1 parent a3c5354 commit a22814e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 19
6+
## Problem Name: Remove Nth Node From End of List
7+
##===================================
8+
#
9+
#Given a linked list, remove the n-th node from the end of list and return its head.
10+
#
11+
#Example:
12+
#
13+
#Given linked list: 1->2->3->4->5, and n = 2.
14+
#
15+
#After removing the second node from the end, the linked list becomes 1->2->3->5.
16+
class Solution:
17+
def removeNthFromEnd(self, head, n):
18+
tmp = head #Initialize tmp
19+
count = 0 #Initialize count
20+
while tmp: #Loop: tmp is not empty, we traverse the list
21+
tmp = tmp.next #point to next node
22+
count += 1 #Increment count by 1
23+
index = count - n #Initialize index which is given equation's result value
24+
previous = None #Initialize previous
25+
point = head #Initialize point
26+
while index != 0: #Loop: index is not zero
27+
previous = point #Assign point to previous
28+
point = point.next #point to next node
29+
index -= 1 #Decrease the index value by 1
30+
if previous is None: #Condition-check: If previous is empty
31+
return head.next #Return head.next
32+
else: #Condition-check: Else
33+
previous.next = point.next #Point point.next to previous.next
34+
point.next = None #Point point.next to none
35+
return head #Return head at the end.

0 commit comments

Comments
 (0)