LeetCode_队列_简单_225.用队列实现栈
2023-09-27 14:25:46 时间
1.题目
请你仅使用两个队列实现一个后入先出(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 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例 1:
输入:
[“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 都保证栈不为空
进阶: 你能否仅用一个队列来实现栈。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
2.思路
(1)队列
参考队列实现栈以及栈实现队列
3.代码实现(Java)
//思路1————队列
class MyStack {
Queue<Integer> queue;
//topElem为栈顶元素
int topElem = 0;
public MyStack() {
queue = new LinkedList<>();
}
//添加元素到栈顶
public void push(int x) {
/*
将队列的队尾看作栈的栈顶
offer(x):向链表末尾添加元素,返回是否成功,成功为true,失败为false
*/
queue.offer(x);
topElem = x;
}
//删除栈顶元素并返回
public int pop() {
//把队尾元素前面的所有元素重新塞到队尾,让队尾元素排到队头,这样就可以取出了
//poll():删除并返回第一个元素
//peek():返回第一个元素
int size = queue.size();
while (size > 2) {
queue.offer(queue.poll());
size--;
}
//记录新的队尾元素
topElem = queue.peek();
queue.offer(queue.poll());
//删除旧的队尾元素
return queue.poll();
}
//返回栈顶元素
public int top() {
return topElem;
}
//判断栈是否为空
public boolean empty() {
return queue.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();
*/
相关文章
- 【LeetCode】数组中两个数的最大异或值 [M](前缀树)
- 【题解】Leetcode HOT100
- LeetCode_前缀树_排序_哈希集合_中等_720.词典中最长的单词
- LeetCode_位运算_简单_268.丢失的数字
- LeetCode_双指针_优先级队列_中等_870.优势洗牌
- LeetCode_单调队列_滑动窗口_中等_239.滑动窗口最大值
- LeetCode_字符串_简单_125.验证回文串
- LeetCode刷题(8)【栈&队列】用栈实现队列(C语言)
- LeetCode刷题(16)【简单】移除链表元素&&回文链表&&删除链表中的结点
- LeetCode·每日一题·862.和至少为 K 的最短子数组·队列+前缀和
- LeetCode·239.滑动窗口最大值·单调队列
- LeetCode·面试题 02.07.链表相交·双指针
- LeetCode·899.有序队列·最小表示法
- Codewars, Leetcode, Hackerrank. Online Judges Reviews
- 【LeetCode从零单排】No22.Generate Parentheses
- LeetCode::Sort List 具体分析
- Leetcode 多维度dp+优先队列+bfs
- 「LeetCode」622. 设计循环队列
- LeetCode-121. 买卖股票的最佳时机(java)
- LeetCode-100. 相同的树(java)
- [LeetCode] 217. Contains Duplicate 包含重复元素
- [LeetCode] 225. Implement Stack using Queues 用队列来实现栈
- LeetCode 26.删除有序数组中的重复项