class MinStack {
Stack<Integer> data;
Stack<Integer> min;
public MinStack() {
data = new Stack<>();//本段代码只能写在构造函数里
min = new Stack<>();
}
public void push(int x) {
data.push(x);
if(min.isEmpty() || min.peek() >= x){
min.push(x);
}
//也可只保存当前的最小值,在pop时判断
}
public void pop() {
if(min.peek() == data.peek())
min.pop();
data.pop();
}
public int top() {
return data.peek();
}
public int min() {
return min.peek();
}
}
class CQueue {
Stack<Integer> A;
Stack<Integer> B;
public CQueue() {
A = new Stack<>();
B = new Stack<>();
}
public void appendTail(int value) {
A.push(value);
}
public int deleteHead() {
//判断是否为空
if(!B.empty())
return B.pop();
else if(A.empty())
return -1;
else {
while(!A.empty()){
int a = A.pop();
B.push(a);
}
return B.pop();
}
}
}
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);//q2接住新节点
//旧的节点依次进来,新的在最前面,所以出队会先出
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
//交换,q2继续当辅助队列。
Queue<Integer> qtemp = q2;
q2 = q1;
q1 = qtemp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
剑指 Offer 30. 包含min函数的栈class MinStack { Stack<Integer> data; Stack<Integer> min; public MinStack() { data = new Stack<>();//本段代码只能写在构造函数里 min = new Stack<>(); } public void push(int x) { data.push(x)