用两个栈实现队列

题目描述

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

栈是先进后出,压入顺序为abc,出栈顺序为cba,压入的顺序和出栈的顺序相反,因此只需要出栈两次,便可

以使得出栈的顺序和压入的顺序一样。两个栈A和B,A负责压入,每次输出的时候,便将A中的数据出栈到B中

然后B再出栈,便能够实现队列的功能。

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(stack1.empty()&&stack2.empty()){
    		return 0;
    	}
        if(!stack2.empty()){
        	return stack2.pop();
        }else{
        	while(!stack1.empty()){
        		stack2.push(stack1.pop());
        	}
        	return stack2.pop();
        }
    }
    
    public boolean empty(){
    	if(stack1.empty()&&stack2.empty()){
    		return true;
    	}else{
    		return false;
    	}
    }
}

扩展:用两个队列实现栈的功能

队列是先进先出,输出的顺序跟输入的顺序是一样的,因此想要逆序输出,就必须先把元素保存,输出最后一个

元素,然后再将保存的元素放回队列。比如队列A和B,A当中有abc,先把ab存入B中,输出c,再将ab保存回A

中。继续这个步骤,就可以实现逆序输出。

public class Solution {
	Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();
    
    public void push(int node){
    	queue1.offer(node);
    }
    
    public int pop(){
    	if(queue1.isEmpty()){
    		return 0;
    	}else{
    		while(queue1.size()>1){
    			queue2.offer(queue1.poll());
    		}
    		int result=queue1.poll();
    		while(!queue2.isEmpty()){
    			queue1.offer(queue2.poll());
    		}
    		return result;
    	}
    }
    
    public boolean isEmpty(){
    	if(queue1.isEmpty()){
    		return true;
    	}else{
    		return false;
    	}
    }
    
}
posted @ 2015-12-28 11:50  黄大仙爱编程  阅读(139)  评论(0)    收藏  举报