package com.hzins.suanfa; import java.util.Stack; /** * 两个stack实现一个queue * @author Administrator * */ public class TwoStackToQueue { private Stack<Integer> stack1; private Stack<Integer> stack2; public TwoStackToQueue(){ stack1 = new Stack<Integer>(); stack2 = new Stack<Integer>(); } /** * 入队 * @param value */ public void push(int value){ stack1.push(value); } /** * 出队 */ public int pop(){ while(!stack2.isEmpty()){ return stack2.pop(); } while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); } public static void main(String[] args) { // Stack<Integer> stack1 = new Stack<Integer>(); // stack1.push(1); // stack1.push(2); // stack1.push(3); // stack1.push(4); // System.out.println(stack1.size()); // System.out.println(stack1.pop()); // System.out.println(stack1.pop()); // System.out.println(stack1.pop()); // System.out.println(stack1.pop()); TwoStackToQueue queue = new TwoStackToQueue(); queue.push(1); queue.push(2); queue.push(3); System.out.println(queue.pop()); System.out.println(queue.pop()); queue.push(4); System.out.println(queue.pop()); } }
时间: 2024-10-11 07:31:32