61. Implement Stack using Queues

来源:互联网 发布:深海逃生剧情 知乎 编辑:程序博客网 时间:2024/05/01 19:46

mplement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

push(x) 入栈:往非空队列的队尾插入元素。

pop() 删除栈顶元素:非空队列的末尾元素应该是需要被弹栈的元素。那么首先把非空队列的前n-1个元素移到另一个空队列中,然后删除剩余的那个元素即可。

top() 返回栈顶元素:非空队列的末尾元素应该是需要被返回的元素。那么首先把非空队列的元素移到另一个空队列中,注意保存第n个元素。

empty() 判断栈是否为空:两个队列同时为空时栈为空。

import java.util.concurrent.ArrayBlockingQueue;class MyStack {        Queue<Integer> Q1 = new ArrayBlockingQueue<Integer>(10);Queue<Integer> Q2 = new ArrayBlockingQueue<Integer>(10);/*     * 往非空的那个队列中添加元素。     */    public void push(int node) {    if(!Q1.isEmpty()){    Q1.add(node);    }else{    Q2.add(node);    }    //System.out.println(Q2);    }    /*     * 出栈操作相当于弹出非空队列的队尾元素。     * 那么首先把非空队列的前n-1个元素移到另一个空队列中,然后弹出剩余的那个元素即可     */    public void pop() {    if(!Q1.isEmpty()){    while(Q1.size()>1){    int node = Q1.poll();    Q2.add(node);    }     Q1.poll();    }else{    while(Q2.size()>1){    int node = Q2.poll();    Q1.add(node);    }    Q2.poll();    }    }        // Get the top element.    public int top() {    int node = 0;    if(!Q1.isEmpty()){    while(Q1.size()>0){    node = Q1.poll();    Q2.add(node);    }        return node;    }else{    while(Q2.size()>0){    node = Q2.poll();    Q1.add(node);    }        return node;    }    }    // Return whether the stack is empty.    public boolean empty() {        return Q1.isEmpty() && Q2.isEmpty();    }        }


0 0
原创粉丝点击