-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackandqueue
More file actions
246 lines (199 loc) · 9.41 KB
/
stackandqueue
File metadata and controls
246 lines (199 loc) · 9.41 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#CS331 Assignment 5, 03/12/2023
# In this assignment, you're asked to implement methods in several classes:
# 1. A Linked-Queue using a Singly LinkedList.
# 2. A Stack that's implemented using one or more Queues.
# 3. A Linked-Stack using a Singly LinkedList.
# You're also asked to implement a method valid_parentheses that uses Linked-Stack.
#################### DO NOT CHANGE THIS CLASS ####################
class Node:
# The Node class for a Singly LinkedList is implemented. Do not change anything in this class.
def __init__(self, val, next = None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self)
# This is the class StackUsingQueue.
# You need to use Queue methods to simulate each method in a Stack.
class StackUsingQueue:
# This is the class Queue, it is implemented using a Singly LinkedList.
class Queue:
# Please implement each of the following methods in class Queue following the guide.
# Here, I've only implemented the construction method and the dunder __repr__ method. Do not change them.
def __init__(self):
# A new Queue contains two pointers head and tail both pointing to None.
#################### DO NOT CHANGE THIS ####################
self.head = self.tail = None
def empty(self):
# Return whether the Queue is empty or not.
return self.head == None
def enqueue(self, item):
# Enqueue item to the tail of the Queue.
# Note that, while enqueuing item to an empty Queue, both head and tail pointers need to be updated.
# Do not return anything in the method.
new = Node(item)
if self.empty():
self.head = new
self.tail = new
else:
holder = self.tail
holder.next = new
self.tail = new
def dequeue(self):
assert not self.empty()
# Dequeue the item at the head of the Queue.
# Note that, after dequeuing the last item, both head and tail pointers need to be updated.
# Return the dequeued item.
self.head = self.head.next
if self.head == None:
self.tail = None
def __iter__(self):
# This implements "for item in Queue"
# Yield each node from head to tail.
# (We don't need to yield node.val since when implemented __repr__(Node) already.)
i = self.head
while i != None:
yield i.val
i = i.next
def __repr__(self):
# This method implements "print(Queue)"
#################### DO NOT CHANGE THIS ####################
return "[" + ",".join(repr(n) for n in self) + "]"
# Please implement each of the following methods in class StackUsingQueue following the guide.
# Remind that, you may use ONLY Queue methods to implement each Stack method in this class.
# Here, our design is that the "head" of self.data (which is a Queue) is the "top" of self (which is a Stack).
# I've only implemented the construction method, peek(), and the dunder __repr__ method. Do not change them.
def __init__(self):
# A new StackUsingQueue contains a Queue as its data.
#################### DO NOT CHANGE THIS ####################
self.data = StackUsingQueue.Queue()
def empty(self):
# Return whether self.data is empty or not.
return self.data.empty()
def peek(self):
# This implementation shows that we consider the "head" of self.data (which is a Queue)
# as the "top" of self (which is a Stack).
#################### DO NOT CHANGE THIS ####################
assert not self.empty()
return self.data.head
def push(self, item):
# Push item to the "top" of self (aka, the "head" of self.data).
# Remind that, you may ONLY use methods in Queue class to implement this method.
# Note that, we cannot insert item directly to the head of a queue.
# Do not return anything in this method.
new = Node(item)
holder = self.data.head
new.next = holder
self.data.head = new
def pop(self):
assert not self.empty()
# Pop out the "top" of self (aka, the "head" of self.data).
# Remind that, you may ONLY use methods in Queue class to implement this method.
# Note that, we can dequeue item directly from the head of a queue.
# Return the popped out item.
holder = self.data.head
self.data.head = self.data.head.next
return holder
def __iter__(self):
# This implements "for item in StackUsingQueue"
# Yield each node from "top" to "bottom" of self (aka, head to tail of self.data).
# (We don't need to yield node.val since when implemented __repr__(Node) already.)
i = self.data.head
while i != None:
yield i
i = i.next
def __repr__(self):
# This method implements "print(StackUsingQueue)"
#################### DO NOT CHANGE THIS ####################
return "[" + ",".join(repr(n) for n in self) + "]"
# This is the class Stack, it is implemented using a Singly LinkedList.
# We have implemented most of the methods in this class in Lecture 7.
class Stack:
# Please implement each of the following methods in class Stack following the guide.
# Here, I've only implemented the construction method and the dunder __repr__ method. Do not change them.
def __init__(self):
# A new Stack contains a pointer called "top" points to None.
#################### DO NOT CHANGE THIS ####################
self.top = None
def empty(self):
# Return whether Stack is empty or not
return self.top == None
def push(self, item):
# Push item to the top of the Stack.
new = Node(item)
holder = self.top
new.next = holder
self.top = new
def pop(self):
assert not self.empty()
# Pop out the top item from Stack.
# Return the popped out item.
holder = self.top
self.top = self.top.next
return holder
def peek(self):
assert not self.empty()
# Return the item on the top of the Stack without popping it out.
return self.top
def __iter__(self):
# This implements "for item in Stack"
# Yield each node from "top" to "bottom" of the Stack.
# (We don't need to yield node.val since when implemented __repr__(Node) already.)
i = self.top
while i != None:
yield i
i = i.next
def __repr__(self):
# This implements "print Stack"
#################### DO NOT CHANGE THIS ####################
return "[" + ",".join(repr(n) for n in self) + "]"
# This is a question on LeetCode https://leetcode.com/problems/valid-parentheses/
# The input of this method is a string that contains "{}", "[]" and "()".
# Return whether the parentheses in the input string is valid or not.
# You should use Stack to solve this question.
def valid_parentheses (expr: str):
parenstack = Stack()
slist = [*expr]
diction = {")" : "(", "]" : "[", "}" : "{"}
for i in slist:
if i == "(" or i == "[" or i == "{":
parenstack.push(i)
elif parenstack.empty() == False and parenstack.peek().val == diction[i]:
parenstack.pop()
else:
return False
return parenstack.empty()
########################################################################################################################
###################################### ############################################
###################################### DO NOT CHANGE ANYTHING BELOW ############################################
###################################### ############################################
########################################################################################################################
print("First, let's test whether the Linked Queue is correctly implemented.")
q1 = StackUsingQueue.Queue()
for x in range (6):
q1.enqueue(x)
print("Let q1 be an empty Linked Queue. After enqueuing numbers 0 ~ 5 to q1, q1 =", q1, ".")
for _ in range(2):
q1.dequeue()
print("After calling dequeue twice, then q1 =", q1, ".")
print("Then, let's test both Stack classes.")
s1 = StackUsingQueue()
for x in range (6):
s1.push(x)
print("Let s1 be an empty Stack implemented with a Queue. After pushing numbers 0 ~ 5 to s1, s1 =", s1, ".")
s2 = Stack()
for x in range (6):
s2.push(x)
print("Let s2 be an empty Linked Stack. After pushing numbers 0 ~ 5 to s2, s2 =", s2, ".")
for _ in range (2):
s1.pop()
s2.pop()
print("Pop out two elements from each Stack, then s1 =", s1, "; and s2 =", s2, ".")
print("In the end, let's test method \"valid_parentheses()\".")
str1 = "{[()](())(){}}{}[]"
print("Let string str1 = " + str1 + ", which is a series of valid parentheses. "
"Our method returns", valid_parentheses(str1), ".")
str2 = "([])}"
print("Let string str2 = " + str2 + ", which is a series of invalid parentheses. "
"Our method returns", valid_parentheses(str2), ".")