剑指 Offer 09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1


class CQueue {Deque<Integer> stackin;Deque<Integer> stackout;public CQueue() {stackin = new LinkedList<>();stackout = new LinkedList<>();}public void appendTail(int value) {stackin.push(value);}public int deleteHead() {if(stackout.isEmpty()){while(!stackin.isEmpty()){stackout.push(stackin.pop());}}// if(!stackout.isEmpty()){// return stackout.pop();// }else{// return -1;// }return !stackout.isEmpty() ? stackout.pop(): -1;}}/*** Your CQueue object will be instantiated and called as such:* CQueue obj = new CQueue();* obj.appendTail(value);* int param_2 = obj.deleteHead();*/
225. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。 实现 MyStack 类: void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。 boolean empty() 如果栈是空的,返回 true ;否则,返回 false

一个队列
.

两个队列
class MyStack {Queue<Integer> queue1;Queue<Integer> queue2;/** Initialize your data structure here. */public MyStack() {queue1 = new LinkedList<Integer>();queue2 = new LinkedList<Integer>();}/** Push element x onto stack. */public void push(int x) {queue2.offer(x);while (!queue1.isEmpty()) {queue2.offer(queue1.poll());}Queue<Integer> temp = queue1;queue1 = queue2;queue2 = temp;}/** Removes the element on top of the stack and returns that element. */public int pop() {return queue1.poll();}/** Get the top element. */public int top() {return queue1.peek();}/** Returns whether the stack is empty. */public boolean empty() {return queue1.isEmpty();}}
347. 前 K 个高频元素
给你一个整数数组
nums和一个整数k,请你返回其中出现频率前k高的元素。你可以按 任意顺序 返回答案。
剑指 Offer 30. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。



class MinStack {Stack<Integer> stack;//实际数据栈Stack<Integer> minStack;//辅助栈,栈顶一直存储当前最小元素,数据个数和实际数据栈中个数一致/** initialize your data structure here. */public MinStack() {stack = new Stack<>();minStack = new Stack<>();}public void push(int x) {stack.push(x);//辅助栈为空或者当前入栈元素小于之前的最小值,说明当前元素就是最小值if(minStack.isEmpty() || x < minStack.peek()){minStack.push(x);}else{//辅助栈顶元素仍然是最小的,让他再次入栈int temp = minStack.peek();minStack.push(temp);}}public void pop() {stack.pop();//数据栈弹出了一个元素,辅助栈相应弹出一个元素minStack.pop();}public int top() {return stack.peek();}public int min() {return minStack.peek();}}/*** Your MinStack object will be instantiated and called as such:* MinStack obj = new MinStack();* obj.push(x);* obj.pop();* int param_3 = obj.top();* int param_4 = obj.min();*/
剑指 Offer 31. 栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
剑指 Offer 59 - II. 队列的最大值
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1





