1. 程式人生 > >如何用兩個棧實現佇列

如何用兩個棧實現佇列

import java.util.Stack;

public class QueueTest {

    private Stack<Integer> inStack=new Stack<>();
    private Stack<Integer> outStack=new Stack<>();
    /**
     * 
     * @Description: (入棧) 
     * @author: liyhui
     * @date: 2018年11月24日
     * @param ele
     */
    public
void enQueue(int ele ) { inStack.push(ele); } /** * * @Description: (出棧) * @author: liyhui * @date: 2018年11月24日 * @param ele */ public Integer deQueue( ) { if(outStack.isEmpty()) { if(inStack.isEmpty()) { return null
; } this.transfer(); } return outStack.pop(); } /** * * @Description: (將入棧的元素給出棧) * @author: liyhui * @date: 2018年11月24日 */ private void transfer() { while(!inStack.isEmpty()) { outStack.push(inStack.pop()); } }
public static void main(String[] args) { QueueTest test=new QueueTest(); test.enQueue(1); test.enQueue(2); test.enQueue(3); System.out.println(test.deQueue()); test.enQueue(4); System.out.println(test.deQueue()); System.out.println(test.deQueue()); System.out.println(test.deQueue()); } }