You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
---
|
|
|
|
栈相关
|
|
|
|
---
|
|
|
|
|
|
|
|
#### [09. 用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class CQueue {
|
|
|
|
|
|
|
|
Stack<Integer> putStack, takeStack;
|
|
|
|
|
|
|
|
public CQueue() {
|
|
|
|
putStack = new Stack<>();
|
|
|
|
takeStack = new Stack<>();
|
|
|
|
}
|
|
|
|
|
|
|
|
public void appendTail(int value) {
|
|
|
|
putStack.push(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
public int deleteHead() {
|
|
|
|
if (takeStack.isEmpty()) {
|
|
|
|
while (!putStack.isEmpty()) {
|
|
|
|
takeStack.push(putStack.pop());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (takeStack.isEmpty()) {
|
|
|
|
return -1;
|
|
|
|
} else {
|
|
|
|
return takeStack.pop();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
#### [30. 包含min函数的栈](https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class MinStack {
|
|
|
|
|
|
|
|
private Node head;
|
|
|
|
|
|
|
|
public MinStack() {
|
|
|
|
}
|
|
|
|
|
|
|
|
public void push(int x) {
|
|
|
|
if (head == null) {
|
|
|
|
head = new Node(x, x, null);
|
|
|
|
} else {
|
|
|
|
Node next = head;
|
|
|
|
head = new Node(x, Math.min(x, next.min), next);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public void pop() {
|
|
|
|
head = head.next;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int top() {
|
|
|
|
return head.val;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int min() {
|
|
|
|
return head.min;
|
|
|
|
}
|
|
|
|
|
|
|
|
class Node {
|
|
|
|
public int val;
|
|
|
|
public int min;
|
|
|
|
public Node next;
|
|
|
|
|
|
|
|
public Node(int val, int min, Node next) {
|
|
|
|
this.val = val;
|
|
|
|
this.min = min;
|
|
|
|
this.next = next;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|