使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
方法:
使用一个队列,利用遍历把新放入的值放在头部,利于使用pop()和top()功能
class MyStack {
Queue<Integer> que;
/** Initialize your data structure here. */
public MyStack() {
que = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
que.add(x);
int num=que.size();
while(num>1){
que.add(que.poll());
num--;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return que.poll();
}
/** Get the top element. */
public int top() {
return que.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return que.isEmpty();
}
}
总结一下关于队列的相关知识
Java中队列:LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
peek()方法,只返回队列首部元素
poll()方法,删除并返回首部元素
offer,add区别:
推荐offer()
一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。
poll,remove区别:
推荐poll()
remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似,但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。
peek,element区别:
推荐peek()
element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。