Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7751d88

Browse files
ybian19azl397985856
authored andcommitted
feat: 232.implement-queue-using-stacks add Python3 implementation (azl397985856#135)
1 parent 870b0ad commit 7751d88

File tree

1 file changed

+53
-3
lines changed

1 file changed

+53
-3
lines changed

‎problems/232.implement-queue-using-stacks.md‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Example:
1616
MyQueue queue = new MyQueue();
1717
1818
queue.push(1);
19-
queue.push(2);
19+
queue.push(2);
2020
queue.peek(); // returns 1
2121
queue.pop(); // returns 1
2222
queue.empty(); // returns false
@@ -64,9 +64,11 @@ push之前是这样的:
6464

6565
## 代码
6666

67-
```js
67+
* 语言支持:JS, Python
6868

69+
Javascript Code:
6970

71+
```js
7072
/*
7173
* @lc app=leetcode id=232 lang=javascript
7274
*
@@ -132,7 +134,55 @@ MyQueue.prototype.empty = function() {
132134
*/
133135
```
134136

137+
Python Code:
138+
139+
```python
140+
class MyQueue:
141+
142+
def __init__(self):
143+
"""
144+
Initialize your data structure here.
145+
"""
146+
self.stack = []
147+
self.help_stack = []
148+
149+
def push(self, x: int) -> None:
150+
"""
151+
Push element x to the back of queue.
152+
"""
153+
while self.stack:
154+
self.help_stack.append(self.stack.pop())
155+
self.help_stack.append(x)
156+
while self.help_stack:
157+
self.stack.append(self.help_stack.pop())
158+
159+
def pop(self) -> int:
160+
"""
161+
Removes the element from in front of queue and returns that element.
162+
"""
163+
return self.stack.pop()
164+
165+
def peek(self) -> int:
166+
"""
167+
Get the front element.
168+
"""
169+
return self.stack[-1]
170+
171+
def empty(self) -> bool:
172+
"""
173+
Returns whether the queue is empty.
174+
"""
175+
return not bool(self.stack)
176+
177+
178+
# Your MyQueue object will be instantiated and called as such:
179+
# obj = MyQueue()
180+
# obj.push(x)
181+
# param_2 = obj.pop()
182+
# param_3 = obj.peek()
183+
# param_4 = obj.empty()
184+
```
185+
135186
## 扩展
136187
- 类似的题目有用队列实现栈,思路是完全一样的,大家有兴趣可以试一下。
137188
- 栈混洗也是借助另外一个栈来完成的,从这点来看,两者有相似之处。
138-

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /