栈
先进后出
队列
先进先出
用栈实现队列
java 中有stack 和Deque 两种类型可以实现栈
java
class MyQueue {
Deque<Integer> stack1;
Deque<Integer> stack2;
public MyQueue() {
stack1=new ArrayDeque<Integer>();
stack2=new ArrayDeque<Integer>();
}
public void push(int x) {
stack1.addFirst(x);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int s =stack1.removeFirst();
stack2.addFirst(s);
}
}
return stack2.removeFirst();
}
public int peek() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int s =stack1.removeFirst();
stack2.addFirst(s);
}
}
int ss= stack2.removeFirst();
stack2.addFirst(ss);
return ss;
}
public boolean empty() {
return stack2.isEmpty()&&stack1.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
用队列实现栈
队列有两种类型Deque Queue
java
class MyStack {
Deque<Integer> deque1;
Deque<Integer> deque2;
public MyStack() {
deque1=new ArrayDeque<Integer>();
deque2=new ArrayDeque<Integer>();
}
public void push(int x) {
deque2.offer(x); // 先放在辅助队列中
while (!deque1.isEmpty()){
deque2.offer(deque1.poll());
}
Deque<Integer> queueTemp;
queueTemp = deque2;
deque2 = deque1;
deque1 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
}
public int pop() {
return deque1.poll();
}
public int top() {
return deque1.peek();
}
public boolean empty() {
return deque1.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();
*/