-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathremove.py
58 lines (50 loc) · 1.24 KB
/
remove.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from typing import Optional
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
def removeNthFromEnd(self, head, n):
if not head.next:
return None
front=head
back = head
counter = 0
flag = False
while counter<=n:
if(not front):
flag = True
break
front = front.next
counter+=1
while front:
front = front.next
back = back.next
if not flag:
temp = back.next
back.next = temp.next
temp.next = None
else:
head = head.next
return head
# # Checking in console
if __name__ == '__main__':
head = make_list([1,2,3,4,5])
Instant = Solution()
Solve = Instant.removeNthFromEnd(head, n = 2) # head = make_list([1,2,3,4,5]), n = 2 -> [1,2,3,5, ]
print_list(Solve)