代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回 true
;否则,返回 false
。
注意:
push to back
、peek/pop from front
、size
和 is empty
这些操作。
示例:
输入: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 2, 2, false] 解释: MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // 返回 2 myStack.pop(); // 返回 2 myStack.empty(); // 返回 False
提示:
1 <= x <= 9
100
次 push
、pop
、top
和 empty
pop
和 top
都保证栈不为空
进阶:你能否实现每种操作的均摊时间复杂度为 O(1)
的栈?换句话说,执行 n
个操作的总时间复杂度 O(n)
,尽管其中某个操作可能需要比其他操作更长的时间。你可以使用两个以上的队列。
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.q.append(x)
n = len(self.q)
for i in range(1, n):
self.q.append(self.q.pop(0))
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.q.pop(0)
def top(self) -> int:
"""
Get the top element.
"""
return self.q[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.q) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
class MyStack {
private Deque<Integer> q;
/** Initialize your data structure here. */
public MyStack() {
q = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
q.offerLast(x);
int n = q.size();
while (n-- > 1) {
q.offerLast(q.pollFirst());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.pollFirst();
}
/** Get the top element. */
public int top() {
return q.peekFirst();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。