-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacks.py
91 lines (79 loc) · 2.07 KB
/
stacks.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
# LIFO - last in, first out
# Use the "end" for adding and removing with a list, because O(1)
# class Node:
# def __init__(self, value):
# self.value = value
# self.next = None
#
#
# class Stack:
# def __init__(self, value):
# new_node = Node(value)
# self.top = new_node
# self.height = 1
#
# def print_stack(self):
# temp = self.top
# while temp is not None:
# print(temp.value)
# temp = temp.next
#
# def push(self, value):
# new_node = Node(value)
# if self.height == 0:
# self.top == new_node
# else:
# new_node.next = self.top
# self.top = new_node
# self.height += 1
#
# def pop(self):
# if self.height == 0:
# return None
# temp = self.top
# self.top = self.top.next
# temp.next = None
# self.height -= 1
# return temp
# Queue: add on one end, remove on another end
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self, value):
new_node = Node(value)
self.first = new_node
self.last = new_node
self.length = 1
def print_queue(self):
temp = self.first
while temp is not None:
print(temp.value)
temp = temp.next
def enqueue(self, value):
new_node = Node(value)
if self.first is None:
self.first = new_node
self.last = new_node
else:
self.last.next = new_node
self.last = new_node
self.length += 1
def dequeue(self):
if self.length == 0:
return None
temp = self.first
if self.length == 1:
self.first = None
self.last = None
else:
self.first = self.first.next
temp.next = None
self.length -= 1
return temp
my_queue = Queue(1)
my_queue.enqueue(2)
print(my_queue.dequeue())
print(my_queue.dequeue())
print(my_queue.dequeue())