栈概述
- 栈的特点:先进后出,后进先出
- 应用
- 浏览器后退功能
- Dijkstra 双栈算术表达式计算器
栈的四种操作
- 访问 Access 时间复杂度 O(1)
访问栈顶元素 - 搜索 Search 时间复杂度 O(N)
需要对栈进行遍历查找 - 插入 Insert 时间复杂度 O(1)
在栈顶插入元素
- 删除 Remove 时间复杂度 O(1)
删除栈顶元素
栈实际的常用操作(Java)
创建栈
//Create a stackStack<Integer> stack = new Stack<>();
添加元素
//Add element//Time Complexity:O(1)stack.push(1);stack.push(2);stack.push(3);//[1,2,3]System.out.println(stack.toString());
获取栈顶元素
//Get the top of stack// Time Complexity:O(1)//3stack.peek();
删除栈顶元素
//Remove the top of stack//Time Complexity:O(1)int temp = stack.pop();//3System.out.println(temp);
栈的大小
//Stack length//Time Complexity:O(1)//2stack.size();
栈是否为空
//Stack is empty?//Time Complexity:O(1)//falsestack.isEmpty();
遍历栈
//Iterate a stack 边删除边遍历//Time Complexity:O(N)while (!stack.isEmpty()) {int num = stack.pop();System.out.println(num);}
LeetCode练习
#20
**#496
参考:https://www.bilibili.com/read/cv8687919?spm_id_from=333.788.b_636f6d6d656e74.10
