-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist-scratch-python.py
More file actions
110 lines (95 loc) · 2.82 KB
/
linkedlist-scratch-python.py
File metadata and controls
110 lines (95 loc) · 2.82 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
class Node:
# constructor
def __init__(self, data=None):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
if(self.head == None):
return True
# insertion method for the linked list
def push(self, data):
newNode = Node(data)
if(self.head):
current = self.head
while(current.next): #finding the tail
current = current.next
current.next = newNode #insert behind the tail
else:
self.head = newNode #if no head, then its's our first node!
def head_insert(self, data):
newNode = Node(data)
if(self.head):
current = self.head
newNode.next = current.next
current.next = newNode
else:
self.head = newNode
def insert(prevNode, data):
if(prevNode == None):
print("The given previous node is not valid")
return data
newNode = Node(data)
newNode.next = prevNode.next
prevNode.next = newNode
def delete(self, data):
if(self.head.data == data):
queue_pop()
prevNode = self.head
current = prevNode.next
while(current):
if(current.data == data):
prevNode.next = current.next
current.next = None
break
prevNode = current
current = current.next
if(current == None):
print("The given data is not here")
def stack_pop(self):
current = self.head
prevNode = None
while(current.next):
prevNode = current
current = current.next
prevNode.next = None
return current
def queue_pop(self):
temp = self.head
self.head = self.head.next
return temp
# edit data
def edit(node, newData):
node.data = newData
def edit_by_val(self, oldData, newData):
current = self.head
while(current):
if(oldData == current.data):
current.data = newData
break
current = current.next
# print method for the linked list
def printLL(self):
current = self.head
while(current):
print(current.data)
current = current.next
print()
# Single Linked List with insertion and print methods
LL = SingleLinkedList()
LL.push(1)
LL.push(2)
LL.push(3)
LL.push(4)
LL.push(5)
LL.printLL()
LL.stack_pop()
LL.printLL()
LL.queue_pop()
LL.printLL()
LL.edit_by_val(3, 7)
LL.printLL()
LL.delete(7)
LL.printLL()