-
Notifications
You must be signed in to change notification settings - Fork 70
/
delete_linked_list_node.py
76 lines (58 loc) · 1.36 KB
/
delete_linked_list_node.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Node:
# Initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Initialize head
def __init__(self):
self.head = None
# Insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Delete the node at a given position
def deleteNode(self, position):
# If linked list is empty
if self.head == None:
return
# Store head node
temp = self.head
# If head needs to be removed
if position == 0:
self.head = temp.next
temp = None
return
# Find previous node of the node to be deleted
for i in range(position -1 ):
temp = temp.next
if temp is None:
break
# If position is more than number of nodes
if temp is None:
return
if temp.next is None:
return
# Node temp.next is the node to be deleted
# store pointer to the next of node to be deleted
next = temp.next.next
# Unlink the node from linked list
temp.next = None
temp.next = next
def printList(self):
temp = self.head
while(temp):
print " %d " %(temp.data),
temp = temp.next
llist = LinkedList()
llist.push(8)
llist.push(2)
llist.push(7)
llist.push(1)
llist.push(9)
print "Created Linked List: "
llist.printList()
llist.deleteNode(3)
print "\nLinked List after Deletion at position 4: "
llist.printList()