-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremoveNodeFromLinkedList.py
53 lines (41 loc) · 1.35 KB
/
removeNodeFromLinkedList.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
iterate over list, increment counter, identify the size of the list
ith node = size_of_list - n + 1
if (i = 1):
# remove the last element
elif (i is between 1 and n exclusively):
# remove middle
elif (i == n):
# remove last element
"""
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
size_of_list = 0
curNode = head
while (curNode != None):
size_of_list += 1
curNode = curNode.next
node_for_deletion = size_of_list-n+1
ctr = 1
if (node_for_deletion == 1):
return head.next
elif (1 < node_for_deletion < size_of_list):
curNode = head
while (curNode != None):
if (ctr == node_for_deletion-1):
curNode.next = curNode.next.next
curNode = curNode.next
ctr += 1
elif (node_for_deletion == size_of_list):
curNode = head
while (curNode != None):
if (ctr == node_for_deletion-1):
curNode.next = None
curNode = curNode.next
ctr += 1
return head