-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHW4.py
More file actions
60 lines (47 loc) · 1.31 KB
/
HW4.py
File metadata and controls
60 lines (47 loc) · 1.31 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
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
last = self.stack[-1]
self.stack.pop()
return last
def peek(self):
return self.stack[-1]
def isEmpty(self):
return not self.stack
class MyQueue:
def __init__(self):
self.first_stack = Stack()
self.second_stack = Stack()
def enqueue(self, item):
self.first_stack.push(item)
def dequeue(self):
if self.second_stack.isEmpty():
while self.first_stack.stack:
item = self.first_stack.pop()
self.second_stack.push(item)
last = self.second_stack.pop()
return last
def peek(self):
if self.second_stack.isEmpty():
while self.first_stack.stack:
item = self.first_stack.pop()
self.second_stack.push(item)
last = self.second_stack.peek()
return last
def isEmpty(self):
empty = self.first_stack.isEmpty() and self.second_stack.isEmpty()
return empty
q = MyQueue()
q.enqueue(5)
q.enqueue(25)
q.enqueue(30)
print(q.peek())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.isEmpty())
q.enqueue(70)
print(q.peek())