题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
这个用python不知道怎么做,就用java吧,参考大神思路
用两个栈实现一个队列的功能?要求给出算法和思路!
<分析>:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;
如果不为空,栈B直接出栈。
其实入栈就是直接压进A,出栈稍麻烦,因为队列是先进先出,要把A栈底的元素先拿出来,那么就把A栈中的元素一一弹出,并且按照顺序压进B栈
,这样A栈底的元素就变成B栈顶的元素了,就符合队列的特点了。敲了一下,
/**
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
* <分析>:
* 入队:将元素进栈A
* 出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈; 如果不为空,栈B直接出栈。
*
* @author XIAO
*
*/
import java.util.Stack;
public class StackQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
int a;
if (!stack2.isEmpty()) {
a = stack2.pop();
} else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
a = stack2.pop();
}
return a;
}
}
用两个队列实现一个栈的功能?要求给出算法和思路!
<分析>:把B当做一个中转站
入栈:将元素进队列A
出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列,否则将队列A中的元素出队列并放入队列B,直到队列A中的元素留下一个,
然后队列A出队列,再把 队列B中的元素出队列以此放入队列A中。
public class QueueStack {
Queue<Integer> queue1 = new ArrayDeque<>();
Queue<Integer> queue2 = new ArrayDeque<>();
public void push(int node) {
// 两个栈都为空时,优先考虑queue1
if (queue1.isEmpty() && queue2.isEmpty()) {
queue1.add(node);
return;
}
// 如果queue1为空,queue2有元素,直接放入queue2
if (queue1.isEmpty()) {
queue2.add(node);
return;
}
if (queue2.isEmpty()) {
queue1.add(node);
return;
}
}
public int pop() {
// 两个栈都为空时,没有元素可以弹出
if (queue1.isEmpty() && queue2.isEmpty()) {
try {
throw new Exception("stack is empty");
} catch (Exception e) {
}
}
// 如果queue1为空,queue2有元素, 将queue2的元素依次放入queue1中,直到最后一个元素,我们弹出。
if (queue1.isEmpty()) {
while (queue2.size() > 1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
if (queue2.isEmpty()) {
while (queue1.size() > 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}
return (Integer) null;
}
}