232.用栈实现队列
力扣原题链接
思路:用双栈模拟队列,双栈分别为入栈和出栈,入队直接push进入栈,出队时先判断出栈是否为空,若为空把入栈的全部元素加到出栈里再 pop 第一个出栈元素,若不为空则直接 pop 第一个出栈元素,peek 时记得代码复用,因为使用了判断出栈是否为空的代码,这里单独写成一个 private 方法。
import java.util.Stack;
public class My_Queue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
/** Initialize your data structure here. */
public My_Queue() {
stackIn = new Stack<>(); // 负责进栈
stackOut = new Stack<>(); // 负责出栈
}
/** Push element x to the back of queue. */
public void push(int x) {
stackIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
dumpstackIn();
return stackOut.pop();
}
/** Get the front element. */
public int peek() {
dumpstackIn();
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
225. 用队列实现栈
力扣原题链接
思路1:只用一个队列实现栈,入栈时始终把该元素放到队列的最前面,这样每次出栈时就是最后一次加入的元素了。
import java.util.LinkedList;
import java.util.Queue;
public class My_Stack {
Queue<Integer> queue;
public My_Stack() {
queue = new LinkedList<>();
}
public void push(int x) {
// offer()方法相对于add,在队满情况下加入元素,add() 方法就会抛出一个 unchecked 异常,而调用 offer() 方法会返回false,
// 因此就可以在程序中进行有效的判断。
queue.offer(x);
int size = queue.size();
while (size-- > 1) {
// 如果队列元素为空,调用remove() 的行为与 Collection 接口的版本相似会抛出异常,
// 但是新的 poll() 方法在用空集合调用时只是返回 null。因此新的方法更适合容易出现异常条件的情况。
queue.offer(queue.poll()); // poll返回第一个元素,并在队列中删除
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek(); // 与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。
}
public boolean empty() {
return queue.isEmpty();
}
}
思路2:只用一个队列实现栈,入栈时直接把元素放到队列里,出栈时把最后一个元素放到队列最前面,具体操作为把队列 size-1 的元素依次重新加入到队列后面再把前面的删除。
import java.util.ArrayDeque;
import java.util.Deque;
public class My_Stack {
Deque<Integer> que1;
/** Initialize your data structure here. */
public My_Stack() {
que1 = new ArrayDeque<>();
}
/** Push element x onto stack. */
public void push(int x) {
que1.addLast(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = que1.size();
size--;
// 将 que1 导入 que2 ,但留下最后一个值
while (size-- > 0) {
que1.addLast(que1.peekFirst());
que1.pollFirst();
}
int res = que1.pollFirst();
return res;
}
/** Get the top element. */
public int top() {
return que1.peekLast();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return que1.isEmpty();
}
}