您的位置:首页 > 产品设计 > UI/UE

Implement Stack using Queues

2016-02-23 19:37 393 查看

题目描述

Implement 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.

题目解答

解题思路

代码实现

class MyStack {
ArrayDeque<Integer> queue = new ArrayDeque<>();
// Push element x onto stack.
public void push(int x) {

ArrayDeque<Integer> tmp = new ArrayDeque<>();
tmp.add(x);
while(!queue.isEmpty()) {
tmp.add(queue.remove());
}
queue = tmp;

}

// Removes the element on top of the stack.
public void pop() {
queue.remove();
}

// Get the top element.
public int top() {
return queue.peek();
}

// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: