-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNodeFromEndOfLinkedList.py
More file actions
43 lines (35 loc) · 957 Bytes
/
RemoveNodeFromEndOfLinkedList.py
File metadata and controls
43 lines (35 loc) · 957 Bytes
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
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printLinkedList(head):
current = head
while current:
print(current.val, end=" → ")
current = current.next
print("None")
def removeNthFromEnd(head, n):
current, length, count = head, 0, 0
while current:
length += 1
current = current.next
prev = head
newnode = head.next
if head is None:
return
elif (length - n) == 0:
head = head.next
return head
else:
while newnode:
if count == (length-n)-1:
prev.next = newnode.next
prev = newnode
newnode = newnode.next
count += 1
return head
head = ListNode(1)
head.next = ListNode(2)
'''head.next.next = ListNode(3)
head.next.next.next = ListNode(4)'''
printLinkedList(removeNthFromEnd(head,1))