两个栈实现一个队列
思路:所有元素进stack1,然后全部出stack1并进入stack2.实现队列的先进先出即:若stack2非空,我们需要的恰好再栈顶,出栈;
若要给队列添加元素,即先进sack1,要出队时,若stack2不为空就出栈,为空时就把stack1全部进栈到stack2
class Stack{
int top;
int[]elem;
public Stack(){
this(10);
}
public Stack(int size){
this.elem=new int[size];
this.top=0;
}
public boolean isFull(){
if(this.top==this.elem.length){
return true;
}
return false;
}
public boolean push(int val){
if(isFull()){
return false;
}
this.elem[this.top++]=val;
return true;
}
public boolean isEmpty(){
if(this.top==0){
return true;
}
return false;
}
public int pop(){
if(isEmpty()){
return -1;
}
--this.top;
return this.elem[this.top];
}
}
public class Solution1 {
Stack stack1=new Stack();
Stack stack2=new Stack();
public void insertTail(int x){//添加元素到队尾 --进队---
stack1.push(x);
}
public boolean isEmpty1(){
if(stack1.top==0&&stack2.top==0){
return true;
}
return false;
}
public int pop1(){//删除队首 --出队--- 必须是队不为空才能删除
if( !isEmpty1()){//队列不为空
if(stack2.isEmpty()){//若stack2为空,则把stack1全部加入stack2
stack1ToStack2();
}
return stack2.pop();
}else{
System.out.println("队列已经为空,不能执行从队头出队");
return -1;
}
}
public void stack1ToStack2(){//把stack1全部放入stack2
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution1 q=new Solution1 ();
q.insertTail(1);
q.insertTail(2);
q.insertTail(3);
q.insertTail(4);
System.out.println(q.pop1());
System.out.println(q.pop1());
q.insertTail(5);
System.out.println(q.pop1());
System.out.println(q.pop1());
System.out.println(q.pop1());
System.out.println(q.pop1());
}
}