题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
编程思路
通过一个具体的例子来分析该队列插入和删除元素的过程。首先插入一个元素a,不妨先把它插入到stack1,此时stack1 中的元素有{a},stack2为空。再压入两个元素b和c,还是插入到stack1中,此时stack1中的元素有{a,b,c},其中c位于栈顶,而stack2仍然为空。
这个时候,我们试着删除从队列中删除一个元素。按照队列先入先出的规则,由于a比b、c先插入到队列中,最先被删除的元素应该是a。元素a存储在stack1中,但并不在占顶上,因此不能直接被删除。注意到stack2我们还一直没有使用过,现在是让stack2发挥作用的时候了。如果我们把stack1中的元素逐个弹出并压入stack2,元素在stack2中的顺序正好和原来的stack1中的顺序相反。因此经过3次弹出stack1和压入stack2操作之后,stack1为空,而stack2中的元素是{c,b,a},这个时候就可以弹出stack2的栈顶a了。此时的stack1为空,而stack2的元素为{c,b},其中b在栈顶,如图所示:
程序代码(Java语言)
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.size() <= 0) {
while(stack1.size() > 0) {
int data = stack1.pop().intValue();
stack2.push(data);
}
}
if(stack2.size() == 0){
System.out.println("queue is empty");
return -1;
}
int head = stack2.pop().intValue();
return head;
}
}
相关题目
编程思路
如图所示,我们先往栈内压入一个元素a。由于两个队列现在都是空,我们可以选择把a插入两个队列中的任一个。我们不妨把a插入queue1。接下来继续网栈内压入b,c两个元素。我们把它们都插入queue1。这个时候 queue1包含3个元素a,b,c其中a位于队列的头部,c位于队列的尾部。
现在我们考虑从栈内弹出一个元素。根据栈的后入先出的原则,最后被压入栈的c应该最先被弹出。由于c位于queue1的尾部,而我们每次只能从队列的头部删除元素,因此我们可以从queueu中依次删除a/b/c并插入到queue2中,再从queue1中删除c。这就相当于从栈中弹出元素c了。我们可以用同样的方法从栈内弹出元素b。
接下来我们考虑从栈内压入一个元素d.此时queue1已经有了一个元素,我们就把d插入到queue1的尾部。如果我们再从栈内弹出一个元素,此时被弹出的应该是最后被压入的d.由于d位于queue1的尾部,我们只能先从头部删除 queue1的元素并插入到queue2,直到queue1中遇到d再直接把它删除。如图所示:
程序代码(Java语言)
package 两个一个队列实现一个栈;
import java.util.LinkedList;
public class Test {
LinkedList<Integer> queue1 = new LinkedList<Integer>();
LinkedList<Integer> queue2 = new LinkedList<Integer>();
public int push(int node) {
if(queue1.size() ==0 && queue2.size() == 0){
queue1.addLast(node);
}else if(queue1.size()!=0){
queue1.addLast(node);
}else if(queue2.size()!=0){
queue2.addLast(node);
}
return node;
}
public int pop() {
int re =0;
if(queue1.size() == 0 && queue2.size() == 0){
return 0;
}
if(queue2.size() == 0){
while(queue1.size() >0){
re = queue1.removeFirst();
if(queue1.size() != 0){
queue2.addLast(re);
}
}
}else if(queue1.size() == 0){
while(queue2.size() >0){
re = queue2.removeFirst();
if(queue2.size()!=0){
queue1.addLast(re);
}
}
}
return re;
}
public static void main(String[] args) {
Test stack=new Test();
int tmp;
stack.push(1);
stack.push(2);
stack.push(3);
tmp=stack.pop();
System.out.println(tmp);//3
stack.push(4);
tmp=stack.pop();
System.out.println(tmp);//4
tmp=stack.pop();
System.out.println(tmp);//2
stack.push(5);
stack.push(6);
tmp=stack.pop();
System.out.println(tmp);//6
tmp=stack.pop();
System.out.println(tmp);//5
tmp=stack.pop();
System.out.println(tmp);//1
}
}
`