-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stacks and Queues.py
109 lines (90 loc) · 2.63 KB
/
Stacks and Queues.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push_to_stack(self, value):
if not isinstance(value, Node):
value = Node(value)
if self.is_empty():
self.head = value
else:
old = self.head
self.head = value
self.head.next = old
def pop(self):
if not self.is_empty():
old = self.head
self.head = self.head.next
old.next = None
return old.data
else:
return "Stack is empty"
def is_empty(self):
return self.head is None # Returns boolean True or False
# function to return head/ stack pointer of stack
def peek(self):
if not self.is_empty():
return self.head.data
else:
return "Stack is empty"
def __str__(self):
print("--Stack--")
output = ""
current = self.head
while current is not None:
output += str(current.data) + "->"
current = current.next
if output:
return "[" + output[:-2] + "]"
return "[]"
class Queue:
def __init__(self):
self.head = None
self.tail = None
# Append value to the tail of queue
def append_value(self, value):
if not isinstance(value, Node):
value = Node(value)
if self.is_empty():
self.head = value
else:
self.tail.next = value
self.tail = value
# Remove first value in queue
def remove(self):
if not self.is_empty():
old = self.head
self.head = self.head.next
old.next = None
return old.data
else:
return "Queue is empty"
def is_empty(self):
return self.head is None # Returns boolean True or False
def peek(self):
if not self.is_empty():
return self.head.data
else:
return "Queue is empty"
def __str__(self):
print("--Queue--")
output = ""
current = self.head
while current is not None:
output += str(current.data) + "->"
current = current.next
if output:
return "[" + output[:-2] + "]"
return "[]"
my_stack = Stack()
my_queue = Queue()
for i in range(1, 6):
my_stack.push_to_stack(i)
my_queue.append_value(i)
my_stack.pop()
my_queue.remove()
print(my_stack)
print(my_queue)