-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackAndQueue.py
More file actions
125 lines (116 loc) · 3.35 KB
/
StackAndQueue.py
File metadata and controls
125 lines (116 loc) · 3.35 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
# 225. Implement Stack Using Queue
# 232. Implement Queue Using Stack
class MyStack:
# 使用双队列
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = []
self.q2 = []
# q2为空,则加入到q1中,反之亦然
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
if not self.q2:
self.q1.append(x)
elif not self.q1:
self.q2.append(x)
# 加入q1不为空,则将q1中元素按顺序压入到q2中,并将q1的最后一个元素删除并返回
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if self.q1:
while len(self.q1) >= 2:
self.q2.append(self.q1[0])
del self.q1[0]
top = self.q1[0]
del self.q1[0]
return top
if self.q2:
while len(self.q2) >= 2:
self.q1.append(self.q2[0])
del self.q2[0]
top = self.q2[0]
del self.q2[0]
return top
# 与pop操作类似,区别在于最后一个元素要压入另一个队列中
def top(self):
"""
Get the top element.
:rtype: int
"""
if self.q1:
while len(self.q1) >= 2:
self.q2.append(self.q1[0])
del self.q1[0]
top = self.q1[0]
del self.q1[0]
self.q2.append(top)
return top
if self.q2:
while len(self.q2) >= 2:
self.q1.append(self.q2[0])
del self.q2[0]
top = self.q2[0]
del self.q2[0]
self.q1.append(top)
return top
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
if self.q1 or self.q2:
return False
else:
return True
class MyQueue:
# 使用双堆栈,一个用来push时存放元素,一个用来pop和peek
def __init__(self):
"""
Initialize your data structure here.
"""
self.pushStack = []
self.popStack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.pushStack.append(x)
# pop堆栈空时,将第一个stack中的元素按LIFO顺序推入第二个stack中,这样stack中的元素按逆序进入第二个stack,并将栈顶推出。
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if not self.popStack:
while self.pushStack:
self.popStack.append(self.pushStack.pop())
x = self.popStack.pop()
return x
def peek(self):
"""
Get the front element.
:rtype: int
"""
if not self.popStack:
while self.pushStack:
self.popStack.append(self.pushStack.pop())
return self.popStack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if self.pushStack or self.popStack:
return False
else:
return True