155-最小栈
思路:
- minStack 只放入最小值。
- minStack 和 dataStack 同时放入值。
代码:
public class MinStack_155 {
Deque<Integer> xStack;
Deque<Integer> minStack;
/** initialize your data structure here. */
public MinStack_155() {
xStack = new LinkedList<>();
minStack = new LinkedList<>();
minStack.push(Integer.MAX_VALUE);
}
public void push(int val) {
xStack.push(val);
if (!minStack.isEmpty())
minStack.push(Math.min(val, minStack.peek()));
else
minStack.push(val);
}
public void pop() {
if (!xStack.isEmpty() && !minStack.isEmpty()) {
xStack.pop();
minStack.pop();
}
}
public int top() {
return xStack.peek();
}
public int getMin() {
return minStack.peek();
}
public static void main(String[] args) {
MinStack_155 minStack = new MinStack_155();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
System.out.println(minStack.getMin()); //--> 返回 -3.
minStack.pop();
System.out.println(minStack.top()); //--> 返回 0.
System.out.println(minStack.getMin()); //--> 返回 -2.
}
}
232-用栈实现队列
代码:
public class StackToQueue_232 {
Deque<Integer> inStack;
Deque<Integer> outStack;
public StackToQueue_232() {
inStack = new LinkedList<>();
outStack = new LinkedList<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
public void in2out () {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
public static void main(String[] args) {
StackToQueue_232 myQueue = new StackToQueue_232();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
// myQueue.printQueue();
System.out.println(myQueue.peek()); // return 1
System.out.println(myQueue.pop()); // return 1, queue is [2]
System.out.println(myQueue.pop());
System.out.println(myQueue.empty()); // return false
}
}
225-用队列实现栈
代码:
public class QueueToStack_225 {
/**
* queue1 作为出栈元素的队列
* queue2 作为入栈元素的辅助队列,并且入栈操作后 queue2 永远是空队列
*/
Queue<Integer> queue1;
Queue<Integer> queue2;
public QueueToStack_225() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue2.offer(x);
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
// 交换 queue1 和 queue2 队列
Queue<Integer> tmp = queue1;
queue1 = queue2;
queue2 = tmp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
public static void main(String[] args) {
QueueToStack_225 myStack = new QueueToStack_225();
myStack.push(1);
myStack.push(2);
System.out.println(myStack.top()); // 返回 2
System.out.println(myStack.pop()); // 返回 2
myStack.empty(); // 返回 False
}
}