码迷,mamicode.com
首页 > 其他好文 > 详细

CTCI 3.5

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

标签:style   blog   java   color   os   div   

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

标签:style   blog   java   color   os   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!