Stack编程队列

题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

首先定义两个栈

Stack<Integer> stack1 = new Stack<Integer>();//作为进队的端口
Stack<Integer> stack2 = new Stack<Integer>();//作为出对的端口

思路:两个栈,有两个端口,那么肯定一个是用来入队的,另一个用来出队的。同时,由于栈是先进后出的,那么经过两次的入栈则会变为先进先出,即,第一次先进后出,第二次后进先出,两个加起来就变成了先进先出。

故,入队时,
为了保证队中的元素在当前元素之前,我们先从s2出栈,进入s1.

具体看代码:很简单

 1 public void push(int node) {
 2         //检查是否满了?
 3 
 4         //将s2中的元素出栈,进栈到s1中
 5         while(!stack2.isEmpty()){
 6             int x = stack2.pop();
 7             stack1.push(x);
 8         }
 9 
10         //node元素进栈
11         stack1.push(node);
12 
13         //stack1中全体元素出栈,进入stack2中
14         while(!stack1.isEmpty()){
15             int x = stack1.pop();
16             stack2.push(x);
17         }
18     }
19 
20   public int pop() {
21 
22     if(!stack2.isEmpty()){
23         int x = stack2.pop();
24         return x;
25     }else{
26         return -1;
27     }
28 }

当然这是从进队入手,出队简化。反之,我们也可以简化入队而让出队时考虑到应有情况。代码如下:

 1 public void push(int node) {
 2         stack1.push(node);
 3     }
 4 
 5    public int pop() {
 6 
 7     //检查s2是否为空
 8     if(stack2.isEmpty()){
 9         //从stack1弹出元素并压入stack2
10         while(!stack1.isEmpty()){
11             int x = stack1.pop();
12             stack2.push(x);
13         }
14 
15 
16     }
17 
18     //出队
19     int head = stack2.pop();
20     return head;
21 }

相比之下,第二个方法更简单一些。

原文地址:https://www.cnblogs.com/shamo89/p/7070302.html