232. 用栈实现队列
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() {
stackChange();
Integer pop = stackOut.pop();
return pop;
}
public int peek() {
stackChange();
Integer peek = stackOut.peek();
return peek;
}
public boolean empty() {
return stackOut.isEmpty() && stackIn.isEmpty();
}
public void stackChange() {
if(!stackOut.isEmpty()) return; // 自己的代码少了这里
while (!stackIn.isEmpty()) {
Integer head = stackIn.pop();
stackOut.push(head);
}
}
}
所以说!!! 思路很重要
225. 用2个队列实现栈
这个写了15分钟写出来
class MyStack {
Queue<Integer> queueIn;
Queue<Integer> queueBackUp;
public MyStack() {
queueIn = new LinkedList<>();
queueBackUp = new LinkedList<>();
}
public void push(int x) {
reBackUp();
queueIn.offer(x);
}
public int pop() {
reBackUp();
while (queueIn.size() > 1) {
Integer front = queueIn.poll();
queueBackUp.offer(front);
}
return queueIn.poll();
}
public int top() {
reBackUp();
while (queueIn.size() > 1) {
Integer front = queueIn.poll();
queueBackUp.offer(front);
}
return queueIn.peek();
}
public boolean empty() {
return queueIn.size() == 0 && queueBackUp.size() == 0;
}
private void reBackUp() {
while (queueIn.size() != 0) {
queueBackUp.offer(queueIn.poll());
}
Queue<Integer> tmp = queueIn;
queueIn = queueBackUp;
queueBackUp = tmp;
}
}
其实第二个队列是纯纯的 backup,可以不要
这个写了3分钟写出来
实际上,一个数(假定它叫X
)入队之后, 是可以 把X
前面的 全部 移到X
的后面.
class MyStack {
Queue<Integer> queue = new LinkedList<>();
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
int move = queue.size() - 1; // 插入一个,前面就是0个,再插入一个前面就是1个
for (int i = 0; i < move; i++) {
queue.offer(queue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
标签:queue,return,int,queueIn,public,QUEUE,queueBackUp,STACK
From: https://www.cnblogs.com/Chain-Tian/p/16954030.html