File tree Expand file tree Collapse file tree 1 file changed +53
-3
lines changed Expand file tree Collapse file tree 1 file changed +53
-3
lines changed Original file line number Diff line number Diff line change @@ -16,7 +16,7 @@ Example:
1616MyQueue queue = new MyQueue();
1717
1818queue.push(1);
19- queue.push(2);
19+ queue.push(2);
2020queue.peek(); // returns 1
2121queue.pop(); // returns 1
2222queue.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-
You can’t perform that action at this time.
0 commit comments