用两个栈实现队列

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

分析
push时将数据插入到第一个栈,当要弹出时,先将第一个栈中所有值弹出,并全部添加到第二个栈中。再弹出第二个栈顶元素,再讲第二个栈剩余值全部弹出到第一个栈。

代码:

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() {
    	while(!stack1.isEmpty()) {
    		stack2.push(stack1.pop());
    	}
    	int temp = stack2.pop();
    	
    	while(!stack2.isEmpty()) {
    		stack1.push(stack2.pop());
    	}
    	return temp;
    }
    
    public static void main(String[] args) {
    	Solution s = new Solution();
    	s.push(1);
    	s.push(2);
    	s.push(3);
    	System.out.println(s.pop());
    	s.push(4);
    	System.out.println(s.pop());
	}
}
原文地址:https://www.cnblogs.com/lishanlei/p/10707759.html