一、概念
栈是一种特殊的线性表,不同于线性表可以在中间位置插入或删除,栈只能在尾部进行增删操作,即只能操作表中的最后一位元素,所以栈是一种先进后出的线性表;
二、基础操作
栈有两种存储方式分别为:顺序存储和链式存储,文末将展示顺序存储的基本实现。
1、入栈:push(x);//将x元素压入栈尾
2、出栈:pop();//注意出栈时要判空,否则会出现空异常
3、查看栈顶元素:peek();//!判空 !
经典例题:
力扣20题、有效括号
. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/valid-parentheses/description/题解:遍历数组,每次遇到左边字符时入栈,例如:(、{、[
遇到右边字符时判断栈内是否有元素,栈空则返回false,反之弹出栈内元素判断,返回结果
最后栈判空(防止左括号剩余
代码:
//左边字符入栈,右出栈
public static boolean isValid(String s) {
if(s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(c == '(' || c == '{' || c == '[') stack.push(c);
if(!stack.isEmpty()) {
if (c == ')' && stack.pop() != '(') return false;
if (c == '}' && stack.pop() != '{') return false;
if (c == ']' && stack.pop() != '[') return false;
}else return false;
}
return stack.isEmpty();
}
三、拓展
用栈实现队列
力扣232题
使用两个栈,栈一:Input、栈二:Out
例如数据:12345(输入顺序1 -> 5)
输入栈一后弹出元素的顺序为,54321
而输入队列弹出元素的顺序为,12345
若将栈一弹出的元素输入栈二,栈二再输出则顺序为,12345
所以当队列输入元素时,我们将元素压入栈一中
输出元素时,将栈一元素压入栈二后再输出,即为正确的队列输出顺序
代码:
<注意:出栈时需要判空>
Stack<Integer> stackInput;//栈一
Stack<Integer> stackOut;//栈二
public MyQueue() {
stackInput = new Stack<>();
stackOut = new Stack<>();
}
//入队
public void push(int x) {
stackInput.push(x);
}
//出队
public int pop() {
in();
return stackOut.pop();
}
//返回开头元素
public int peek() {
in();
return stackOut.peek();
}
//判空
public boolean empty() {
//栈一栈二内都为空,队列才没有数据输出
return stackOut.isEmpty() && stackInput.isEmpty();
}
public void in(){
if(!stackOut.isEmpty()) return;
while (!stackInput.isEmpty()){
stackOut.push(stackInput.pop());
}
}
四、顺序栈的基本实现
public class SqStack{
private Object[] stackElem;
private int top;//栈指针
public SqStack(int maxSize){
stackElem = new Object[maxSize];
top = 0;
}
//置空
public void clear(){
top = 0;
}
//判空
public boolean isEmpty(){
return top == 0;
}
//入栈
public void push(int x){
stackElem[top++] = x;
}
//出栈
public Object pop(){
if (!isEmpty()) return stackElem[top--];
return 0;
}
//查看栈顶元素
public Object peek(){
if (!isEmpty()) return stackElem[top];
return 0;
}
}