[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/wodgithub/algorithm/master/PuzzleCoding/src/QueueByStack.java [Back]  [Original]

import java.util.Stack;

/**
 * Implement a queue with two stacks.
 */
public class QueueByStack {
    private Stack head;
    private Stack tail;

    public QueueByStack() {
        head = new Stack();
        tail = new Stack();
    }

    public void enQueue(T v) {
        head.push(v);
    }

    public T deQueue() {

        if (tail.size() == 0) {
            while (head.size() > 0) {
                tail.push(head.pop());
            }
        }
        if (tail.size() == 0)
            throw new RuntimeException("queue is empty.");

        return tail.pop();
    }

    public static void main(String[] args) {
        QueueByStack queue = new QueueByStack();

        queue.enQueue(2);
        queue.enQueue(5);
        queue.enQueue(1);
        System.out.println(queue.deQueue());
        System.out.println(queue.deQueue());
        System.out.println(queue.deQueue());

    }

}

Web Proxy Viewer  |  New URL  |  Original Page