剑指offer:使用两个栈实现队列

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.isEmpty())
	    	{
	    		//将所有入栈中的元素
	    		while(!stack1.isEmpty())
	    		{
	    			//弹出到出栈中
	    			stack2.push(stack1.pop());
	    		}
	    	}
	    	//出栈不为空则不做处理
	    	
	    	//最后将出栈中的节点弹出
	    	return stack2.pop();
	    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43823363/article/details/87727709