s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1);

### 2.2 判空 - empty()
Stack<Integer> s1 = new Stack<>();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1.empty());

### 2.3 出栈 - pop()
Stack<Integer> s1 = new Stack<>();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1);
s1.pop();
System.out.println(s1);

### 2.4 获取栈顶元素 - peek()
Stack<Integer> s1 = new Stack<>();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1);
s1.peek();
System.out.println(s1);
System.out.println(s1.peek());

### 2.5 获取栈中有效元素个数 - size()
Stack<Integer> s1 = new Stack<>();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
System.out.println(s1.size());

## 三、栈的模拟实现
### 3.1 push
public boolean isFull() {
return this.usedSize == this.elem.length;
}
public void push(int val) {
if (isFull()) {
//扩容
this.elem = Arrays.copyOf(this.elem,2\*this.usedSize);
}
this.elem[this.usedSize] = val;
this.usedSize++;
}
### 3.2 isEmpty
public boolean isEmpty() {
return this.usedSize == 0;
}
### 3.3 pop
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
}
int oldVal = this.elem[usedSize-1];
this.usedSize--;
return oldVal;
}
### 3.4 peek
public int peek() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
}
return this.elem[usedSize-1];
}
### 3.5 MyStack.java
import java.lang.reflect.Array; import java.util.Arrays;
@SuppressWarnings({"all"}) public class MyStack { public int[] elem; public int usedSize;
public MyStack() {
this.elem = new int[5];
}
public void push(int val) {
if (isFull()) {
//扩容
this.elem = Arrays.copyOf(this.elem,2\*this.usedSize);
}
this.elem[this.usedSize] = val;
this.usedSize++;
}
public boolean isFull() {
return this.usedSize == this.elem.length;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
}
int oldVal = this.elem[usedSize-1];
this.usedSize--;
return oldVal;
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
}
return this.elem[usedSize-1];
}
public boolean isEmpty() {
return this.usedSize == 0;
}
}
## 四、经典题
### 4.1 有效的括号

class Solution { public boolean isValid(String s) { Stack stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
//如果是左括号 直接入栈
stack.push(ch);
} else {
//遇到了右括号
if (stack.empty()) {
System.out.println("右括号多");
return false;
}
char top = stack.peek();//哪个左括号
if (top == '(' && ch ==')' || top == '[' && ch ==']' || top == '{' && ch =='}') {
stack.pop();
} else {
System.out.println("左右括号不匹配");
return false;
}
}
}
if (!stack.empty()) {
System.out.println("左括号多");
return false;
}
return true;
}
}
### 4.2 逆波兰表达式求值


**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://gitee.com/vip204888)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**