-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackandQueue.py
85 lines (57 loc) · 1.58 KB
/
StackandQueue.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
#array implementation of stack and queue
class Stack():
def __init__(self):
self.array_vals = []
def push(self, value):
self.array_vals.append(value)
def pop(self):
self.array_vals.pop()
class Queue():
def __init__(self):
self.list_vals = []
def enqueue(self, value):
self.list_vals.append(value)
def dequeue(self):
self.list_vals.pop(0)
print(str(self.list_vals))
# Linked List implementation stack and queue
class Node:
def __init__(self, data):
self.data = data
self.nextnode = None
class Stack:
def __init__(self):
self.headnode = None
def push(self, data):
anode = Node(data)
if self.headnode is None:
self.headnode = anode
else:
anode.nextnode = self.headnode.nextnode
self.headnode = anode
def pop(self):
if self.headnode is None:
return None
else:
data = self.headnode.data
self.headnode = self.headnode.nextnode
return data
class Queue:
def __init__(self):
self.headnode = None
def enqueue(self, data):
anode = Node(data)
if self.headnode is None:
self.headnode = anode
else:
nextn = self.headnode
while (nextn.nextnode is not None):
nextn = nextn.nextnode
nextn.nextnode = anode
def dequeue(self):
if self.headnode is None:
return None
else:
data = self.headnode.data
self.headnode = self.headnode.nextnode
return data