232. Implement Queue using Stacks(未完全掌握,待总结,多种方法)
程序员文章站
2022-06-07 09:58:08
...
方法一:
用两个栈,如图示
class MyQueue {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
private int front;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(inStack.isEmpty())
{
front = x;
}
if(outStack.isEmpty())
{
while(!inStack.isEmpty())
{
int tmp = inStack.pop();
outStack.push(tmp);
}
}
inStack.push(x);
while(!outStack.isEmpty())
{
inStack.push(outStack.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int out = inStack.pop();
if(!inStack.isEmpty())
front = inStack.peek();
return out;
}
/** Get the front element. */
public int peek() {
return front;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inStack.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
方法二
入队只需调用Stack的push()方法
出队:
根据栈 LIFO 的特性,s1 中第一个压入的元素在栈底。为了弹出 s1 的栈底元素,我们得把 s1 中所有的元素全部弹出,再把它们压入到另一个栈 s2 中,这个操作会让元素的入栈顺序反转过来。通过这样的方式,s1 中栈底元素就变成了 s2 的栈顶元素,这样就可以直接从 s2 将它弹出了。一旦 s2 变空了,我们只需把 s1 中的元素再一次转移到 s2 就可以了。
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
// Push element x to the back of queue.
public void push(int x) {
if (s1.empty())
front = x;
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if (s2.isEmpty()) {
while (!s1.isEmpty())
s2.push(s1.pop());
}
s2.pop();
}
// Return whether the queue is empty.
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
// Get the front element.
public int peek() {
if (!s2.isEmpty()) {
return s2.peek();
}
return front;
}
上一篇: 7-9 用天平找小球 (10 分) (C语言实现)
下一篇: 7-17 爬动的蠕虫