232.用栈实现队列
这题本质上就是两个栈来实现先进先出,入队列就进入stackin 出队列就stackin pop出去push进入stackout 再进行pop,如果出栈没有元素就把stackin的元素全部导入进去
注意是全部导入,全部导入的目的在于这样你才能将最先入栈的元素最先出栈实现先进先出,不然假设你1,2入栈你只出栈了一个2,但是我队列出队列只弹出一个元素要求的是1就不符合题意了,故代码为while
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn =new Stack<>();
stackOut =new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void dumpstackIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
225. 用队列实现栈
思想就是通过一个辅助队列来实现每次要出栈时候就把queue1中除了最后一个元素全部放到queue2中,这样就可以确保每次都是最后一个元素先出队列实现了栈的先进后出
但是下面的java代码抄自代码随想录可能做了一些优化,是直接push元素的时候就把元素放在queue2,然后再把queue1的元素依次放到queue2 最后再把queue2和queue1交换,就可以保证queue1中的元素都是逆序的,举例假设我要将1入队列 1--->que2 que1为空 que1,que2交换次序,之后que1为1 ,我再把2元素加入进去,那我2--->que2,之后再把que1中的1加入到que2也就是que2变为 21 再交换元素之后,que1就变为21就是相反的顺序,保证了栈的先进后出
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1=new LinkedList<>();
queue2=new LinkedList<>();
}
public void push(int x) {
queue2.offer(x); // 先放在辅助队列中 queue中的offer==add
while (!queue1.isEmpty()){
queue2.offer(queue1.poll()); //queue中的poll==remove
}
Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}