在线编程--包含min函数的栈

本文介绍了一种特殊栈的数据结构实现,该栈除了具备基本的压栈和弹栈功能外,还提供了一个能获取当前栈中最小元素的min函数。通过使用两个栈,一个是数据栈,另一个用于记录每一步的最小值,确保了min函数的时间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

import java.util.Stack;

public class Solution {

    private Stack<Integer> stackDate;
    private Stack<Integer> stackMin;

    public Solution(){
        this.stackDate=new Stack<Integer>();
        this.stackMin=new Stack<Integer>();
    }

    public void push(int node) {
        if(this.stackMin.isEmpty()){
            stackMin.push(node);
        }
        else if(node<this.min()){
            this.stackMin.push(node);
        }
        else{
            this.stackMin.push(top());
        }
        this.stackDate.push(node);
    }

    public void pop() {
        if(this.stackDate.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        this.stackMin.pop();
        this.stackDate.pop();
    }

    public int top() {
        return this.stackMin.peek();
    }

    public int min() {
        if(this.stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        return this.stackMin.peek();
    }
}
### 关于的数据结构编程练习题 #### 题目一:括号匹配验证 给定一个字符串 `s`,该字符串仅由字符 `'('`, `')'`, `'{'`, `'}'`, `'['`, `']'` 构成。编写函数来判断此字符串中的括号是否合法。具体而言,左括号必须按照正确的顺序被相应的右括号闭合。 这是一个经典的应用问题[^2]。可以利用的特性解决此类问题,因为具有后进先出的特点,非常适合处理嵌套关系。 ```python def isValid(s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping.keys(): if not stack or stack.pop() != mapping[char]: return False return not stack ``` --- #### 题目二:最小设计 设计一个支持 `push(x)`、`pop()` 和 `top()` 操作,并能在常数时间内检索到最小元素的。即实现以下方法: - `void push(int val)` 将元素压入中。 - `void pop()` 删除顶元素。 - `int top()` 获取顶元素。 - `int getMin()` 返回中的最小值。 这个问题可以通过辅助的方式高效完成。每次向主中加入新元素时,同时更新辅助以记录当前的最小值[^1]。 ```python class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, x: int) -> None: self.stack.append(x) if not self.min_stack or x <= self.min_stack[-1]: self.min_stack.append(x) def pop(self) -> None: if self.stack.pop() == self.min_stack[-1]: self.min_stack.pop() def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.min_stack[-1] ``` --- #### 颈题目三:表达式求值 给定一个算术表达式的字符串形式(可能包含整数、加减乘除运算符以及括号),计算并返回其最终结果。例如输入 `" (1+(4+5+2)-3)+(6+8)"` 应当返回 `23`。 通过两个分别存储操作数和操作符,逐步解析表达式即可解决问题。 ```python def evaluateExpression(expression: str) -> int: operators = {'+', '-', '*', '/'} precedence = {'+': 1, '-': 1, '*': 2, '/': 2} operand_stack = [] operator_stack = [] i = 0 while i < len(expression): ch = expression[i] if ch.isdigit(): num = "" while i < len(expression) and expression[i].isdigit(): num += expression[i] i += 1 operand_stack.append(int(num)) continue elif ch in operators: while (operator_stack and operator_stack[-1] in precedence and precedence[ch] <= precedence[operator_stack[-1]]): op = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() if op == '+': result = a + b elif op == '-': result = a - b elif op == '*': result = a * b elif op == '/': result = int(a / b) operand_stack.append(result) operator_stack.append(ch) elif ch == '(': operator_stack.append(ch) elif ch == ')': while operator_stack[-1] != '(': op = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() if op == '+': result = a + b elif op == '-': result = a - b elif op == '*': result = a * b elif op == '/': result = int(a / b) operand_stack.append(result) operator_stack.pop() # Remove the '(' from the stack. i += 1 while operator_stack: op = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() if op == '+': result = a + b elif op == '-': result = a - b elif op == '*': result = a * b elif op == '/': result = int(a / b) operand_stack.append(result) return operand_stack[0] ``` --- #### 题目四:逆波兰表示法求值 给定一个有效的逆波兰表达式列表,其中每个元素可能是整数或操作符 (`+`, `-`, `*`, `/`)。评估该逆波兰表达式的值。 逆波兰表达式是一种不需要括号的后缀表达式,适合用来解决。 ```python def evalRPN(tokens: list[str]) -> int: stack = [] for token in tokens: if token.lstrip('-').isdigit(): stack.append(int(token)) else: b = stack.pop() a = stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) elif token == "/": stack.append(int(a / b)) return stack[0] ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值