-
Notifications
You must be signed in to change notification settings - Fork 6
/
linkedListOnlyNodes.py
91 lines (67 loc) · 2.3 KB
/
linkedListOnlyNodes.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# Nodes
# 1. Value - anything strings, integers, objects
# 2. The Next Node
class linkedListNode:
def __init__(self, value, nextNode=None):
self.value = value
self.nextNode = nextNode
def insertNode(head, valuetoInsert):
currentNode = head
while currentNode is not None:
if currentNode.nextNode is None:
currentNode.nextNode = linkedListNode(valuetoInsert)
return head
currentNode = currentNode.nextNode
# Delete node function
def deleteNode(head, valueToDelete):
currentNode = head
previousNode = None
while currentNode is not None:
if currentNode.value == valueToDelete:
if previousNode is None:
newHead = currentNode.nextNode
currentNode.nextNode = None
return newHead
previousNode.nextNode = currentNode.nextNode
return head
previousNode = currentNode
currentNode = currentNode.nextNode
return head # Value to delete was not found.
# "3" -> "7" -> "10"
node1 = linkedListNode("3") # "3"
node2 = linkedListNode("7") # "7"
node3 = linkedListNode("10") # "10"
node1.nextNode = node2 # node1 -> node2 , "3" -> "7"
node2.nextNode = node3 # node2 -> node3 , "7" -> "10"
# node1 -> node2 -> node3
head = node1
print "*********************************"
print "Traversing the regular linkedList"
print "*********************************"
# Regular Traversal
currentNode = head
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "deleting the node '7'"
newHead = deleteNode(head, "10")
print "*********************************"
print "traversing the new linkedList with the node 7 removed"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "Inserting the node '99'"
newHead = insertNode(newHead, "99")
print "*********************************"
print "traversing the new linkedList with the node 99 added"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode