题目解读
使用两个队列来模拟stack 的push、pop()、 top(), isEmpty() 这些基础东西
面试过程当中也是主要
1.push()
2.pop()
3. top()
4. isEmpty()
面试的话主要实现上述几个接口就行了
注意在java 队列当中是没有top()方法的,只有peek(),poll()
在栈stack 当中才有那中top()
队列的api 为poll(), peek(), offer(),主要是这个几个
如果是双向队列
pollFirst() ,pollLast(), peekFirst(), peekLast(), offerFast(), offerLirst()
主要是这两个方面的东西
class MyStack {
/** Initialize your data structure here. */
Queue<Integer> q1;
public MyStack() {
q1 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offer(x);
for(int i=0;i<q1.size()-1;i++){
q1.offer(q1.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.remove();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty()&& q2.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
一个队列实现
当只有一个队列实现的时候,如果采用这种办法的话,如何调整插入的顺序问题, 让后面插入队列的元素进入到队头,实现一个翻转的可能性。
实现过程就是下面这个图
缺陷分析
而第二种解法在push上要花大量的时间,所以适合高频率的top和pop,较少的push。两种方法各有千秋,互有利弊。适合数据量比较少的情况下,
而第二种解法在push上要花大量的时间,所以适合高频率的top和pop,较少的push。两种方法各有千秋,互有利弊。
要注意Java当中队列都只是一接口而已,要注意这点情况即可
两个队列实现
如果使用两个队列的话,要明确两个队列各自的作用
class MyStack {
/** Initialize your data structure here. */
Queue<Integer> q1,q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);// 让q2保持最多只有一个元素的基本情况
while(q2.size()>1){
q1.offer(q2.peek());
q2.poll();
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
// 确保q2当中具有元素就行了,一定要有最基本的元素情况
top();
return q2.poll();
}
/** Get the top element. */
public int top() {
if(q2.isEmpty()){
for(int i=0;i<q1.size()-1;i++){
q1.offer(q1.peek());
q1.poll();
}
q2.offer(q1.peek());
q1.poll();
}
return q2.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
- 使用两个队列来模拟stack,其中一个队列存放stack顶的元素;
- 另一个队列存放的是stack 前面的元素情况,当我们进行stack.pop(), 先判断该队列当中是否具有该元素(特别是针对如何两次都是pop,导致其中一个队列中元素为空,)