题目:Implement Stack using Queues
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.
- You must use only standard operations of a queue -- which means only
push to back,peek/pop from front,size, andis emptyoperations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
class MyStack {
// Push element x onto stack.
private Queue<Integer> q = new LinkedList<>();
public void push(int x)
{
q.add(x);
for(int i = 1; i < q.size(); i ++) { //旋转 把新进元素放在首位
q.add(q.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
q.poll();
}
// Get the top element.
public int top() {
return q.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}
本文介绍了一种使用队列来实现栈数据结构的方法。通过定义一个特殊的MyStack类,该类仅使用队列的基本操作就能完成栈的主要功能,包括push、pop、top以及判断是否为空等。特别地,为了实现栈的先进后出特性,采取了将新加入的元素通过多次队首弹出及队尾加入的操作使其置于队首位置。
371

被折叠的 条评论
为什么被折叠?



