目录
前言:
数据结构想要学的好,刷题少不了,我们不仅要多刷题,还要刷好题!为此我开启了一个必做好题锦集的系列,此为第一篇选择题篇,该系列会不定期更新敬请期待!
栈(Stack)的详解_WHabcwu的博客-CSDN博客
1.进栈过程中可以出栈的选择题
1. 若进栈序列为 1,2,3,4 ,进栈过程中可以出栈,则下列不可能的一个出栈序列是()
A: 1,4,3,2 B: 2,3,4,1 C: 3,1,4,2 D: 3,4,2,1
2.将递归转化为循环
比如:逆序打印链表
使用栈的方法解决:
public void printfList(Node head) {
if (head == null) {
return;
}
Node cur=head;
Stack<Node> stack = new Stack<>();
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
while(!stack.empty()){
System.out.println(stack.pop().val);
}
}
3.逆波兰表达式求值
逆波兰表达式求值https://leetcode.cn/problems/evaluate-reverse-polish-notation/
要想彻底的掌握这道题,必先清楚的理解后缀表达式
总结:
故代码:
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String x : tokens) {
if (!isoperation(x)) {
stack.push(Integer.parseInt(x));
} else {
int x1 = stack.pop();
int x2 = stack.pop();
switch (x) {
case "+":
stack.push(x2 + x1);
break;
case "-":
stack.push(x2 - x1);
break;
case "*":
stack.push(x2 * x1);
break;
case "/":
stack.push(x2 / x1);
break;
}
}
}
return stack.pop();
}
public boolean isoperation(String x) {
if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) {
return true;
}
return false;
}
}
4.有效的括号
有效的括号https://leetcode.cn/problems/valid-parentheses/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char x=s.charAt(i);
if(x=='('||x=='{'||x=='['){
stack.push(x);
}else{
if(stack.empty()){
return false;
}
char y=stack.peek();
if(y=='('&&x==')'||y=='{'&&x=='}'||y=='['&&x==']'){
stack.pop();
}else{
return false;
}
}
}
if(!stack.empty()){
return false;
}
return true;
}
}
解析:
5. 栈的压入、弹出序列
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pushV int整型一维数组
* @param popV int整型一维数组
* @return bool布尔型
*/
public boolean IsPopOrder (int[] pushV, int[] popV) {
Stack<Integer> stack = new Stack<>();
int j=0;
for (int i = 0; i < pushV.length; i++) {
stack.push(pushV[i]);
while(j<popV.length&&!stack.empty()&&stack.peek().equals(popV[j])){
stack.pop();
j++;
}
}
return stack.empty();
}
}
解析:
6. 最小栈
最小栈https://leetcode.cn/problems/min-stack/
import java.util.Stack;
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minstack;
public MinStack() {
this.stack = new Stack<>();
this.minstack = new Stack<>();
}
public void push(int val) {
stack.push(val);
if (minstack.empty()) {
minstack.push(val);
} else {
if (minstack.peek() >= val) {
minstack.push(val);
}
}
}
public void pop() {
if(!stack.empty()){
int x = stack.pop();
if (x == minstack.peek()) {
minstack.pop();
}
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minstack.peek();
}
}
解析:
辅助栈法:
(1)一个用来正常存放数据->stack
(1)一个用来存放最小数据->minstack
push:
stack无差别入栈,对于minstack进行判断,若为空,直接入栈,若不为空,则需要与栈顶元素进行比较,若小于等于则入栈。
其余过于简单,无需多讲。
以上为我个人的小分享,如有问题,欢迎讨论!!!
都看到这了,不如关注一下,给个免费的赞