首页 > 其他 > 详细

CTCI 3.5

时间:2014-07-16 20:39:22      阅读:297      评论:0      收藏:0      [点我收藏+]

Implement a MyQueue class which implements a queue using two stacks.

/*Use two stacks, when enqueue, first pop all the elements in stack2 on stack1, then push the element on
stack1. when dequeue, first pop all elements in stack1 to stack2, then pop an element. Notice that the order
of elements in two stacks are opposite.

*/
import java.util.*;

public class MyQueue {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void enqueue(int key) {
        while(stack2.isEmpty() == false) {
            stack1.add(stack2.pop());
        }
        stack1.add(key);
    }

    public int dequeue() {
        while(stack1.isEmpty() == false) {
            stack2.add(stack1.pop());
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        MyQueue mq = new MyQueue();
        mq.enqueue(1); mq.enqueue(2);
        System.out.println(mq.dequeue());
        mq.enqueue(3);
        System.out.println(mq.dequeue());
        System.out.println(mq.dequeue());
    }
}

 

CTCI 3.5,布布扣,bubuko.com

CTCI 3.5

原文:http://www.cnblogs.com/pyemma/p/3836570.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!