用栈实现队列
入队

出队

class MyQueue { LinkedList<Integer> st1; LinkedList<Integer> st2; public MyQueue() { st1=new LinkedList<>();//出队用的栈 st2=new LinkedList<>();//入队用的栈 } public void push(int x) { st2.push(x); } public int pop() { peek();//防止st1中没有元素 先进行一个peek()操作 return st1.pop(); } public int peek() { if(st1.isEmpty())//如果出队的栈中没有元素了 开始将入队栈中的元素加入出队栈 { while(!st2.isEmpty()) st1.push(st2.pop()); } return st1.peek();//返回队首元素 } public boolean empty() { return st1.isEmpty()&&st2.isEmpty();//两个栈同时为空 }}
用队列实现栈
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1=new LinkedList<>();
q2=new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
//循环结束之后q1为空
while(!q1.isEmpty())
{
q2.offer(q1.poll());
}
//交换之后q2为空
Queue tmp=q1;
q1=q2;
q2=tmp;
}
//下面的操作始终使用q1
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}