225 Implement Stack using Queues

来源:互联网 发布:断电mysql修复 编辑:程序博客网 时间:2024/05/21 10:12
class MyStack {
Queue<Integer> queue = new LinkedList<Integer>();
Queue<Integer> tmp = new LinkedList<Integer>();
    // Push element x onto stack.
    public void push(int x) {
       queue.add(x);
    }


    // Removes the element on top of the stack.
    public void pop() {
        int size = queue.size();
if(size == 0) return;
for(int i=0;i<size-1;++i){
int tval = queue.peek();
tmp.add(tval);
queue.remove();
}
queue.remove();

int tmpSize = tmp.size();
for(int j=0;j<tmpSize;++j){
int tmpVal = tmp.peek();
queue.add(tmpVal);
tmp.remove();
}
    }


    // Get the top element.
    public int top() {
    int topVal = 0;
    int size = queue.size();
for(int i=0;i<size-1;++i){
int tval = queue.peek();
tmp.add(tval);
queue.remove();
}
topVal = queue.peek();
tmp.add(topVal);
queue.remove();

int tmpSize = tmp.size();
for(int j=0;j<tmpSize;++j){
int tmpVal = tmp.peek();
queue.add(tmpVal);
tmp.remove();
}
return topVal;
    }


    // Return whether the stack is empty.
    public boolean empty() {
        return queue.isEmpty();
    }
}
0 0