两个队列实现一个栈,剑指offer P59

public class StackByQueue {
    private LinkedList<String> queue1;
    private LinkedList<String> queue2;
    public StackByQueue() {
        queue1 = new LinkedList<String>();
        queue2 = new LinkedList<String>();
    }
    
    public String pop() {
        String str = null;
        if(queue1.size() ==0 && queue2.size() ==0) {
            return null;
        }
        if(queue2.size() == 0) {
            while(queue1.size() > 0) {
                str = queue1.removeFirst();
                if(queue1.size() != 0) {//要删除的栈元素不会加入队列的尾部
                    queue2.addLast(str);
                }
                
            }
        }else if(queue1.size() == 0){
            while(queue2.size() > 0) {
                str = queue2.removeFirst();
                if(queue2.size() != 0) {
                    queue1.addLast(str);
                }
            }
        }
        return str;
    }
    
    public void push(String str) {
        if(queue1.size() == 0 && queue2.size() == 0) {
            queue1.addLast(str);
        }
        if(queue1.size() != 0) {
            queue1.addLast(str);
        }else if (queue2.size() != 0) {
            queue2.addLast(str);
        }
    }
    
    public static void main(String[] args) {
        StackByQueue stackByQueue  = new StackByQueue();
        stackByQueue.push("1");
        stackByQueue.push("2");
        stackByQueue.push("3");
        System.out.println(stackByQueue.pop());
        stackByQueue.push("8");
        System.out.println(stackByQueue.pop());
    }
    

}

 

posted @ 2016-02-29 19:06  笨狗毒毒毒  阅读(170)  评论(0编辑  收藏  举报