使用两个栈来模拟一个队列和使用两个队列来模拟一个栈

使用两个栈来模拟一个队列

思路

定义两个栈stack1和stack2,队列插入元素永远都push进stack1;当取数据的时候,从stack2取,如果stack2为空,push从stack1中pop的数据,直到stack1为空,如果stack1也为空,那就是队列中已经没有元素,抛出异常。

代码

class MyStack {

/* 队列1 */
private Queue<Integer> queue1;
/* 队列2 */
private Queue<Integer> queue2;

/**
* Initialize your data structure here.
*/
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}

/**
* Push element x onto stack.
*/
public void push(int x) {
if (queue1.isEmpty()) {
queue2.add(x);
} else {
queue1.add(x);
}
}

/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
if (queue1.isEmpty()) {
if (queue2.isEmpty()) {
throw new NullPointerException();
} else {
while (queue2.size() != 1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
} else {
while (queue1.size() != 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}
}

/**
* Get the top element.
*/
public int top() {

int val;
if (queue1.isEmpty()) {
if (queue2.isEmpty()) {
throw new NullPointerException();
} else {
while (queue2.size() != 1) {
queue1.add(queue2.poll());
}
val = queue2.peek();
queue1.add(queue2.poll());
}
} else {
while (queue1.size() != 1) {
queue2.add(queue1.poll());
}
val = queue1.peek();
queue2.add(queue1.poll());
}
return val;
}

/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}

public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
System.out.println(stack.top());
stack.push(3);
System.out.println(stack.top());
}
}