剑指offer-题21:包含min函数的栈

时间:2021-09-09 22:53:23

题目描述

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

实验平台:牛客网


解决思路:

剑指offer-题21:包含min函数的栈
剑指offer-题21:包含min函数的栈
剑指offer-题21:包含min函数的栈

java:

import java.util.Stack;

public class Solution {
    Stack<Integer> minStack = new Stack<>();
    Stack<Integer> dataStack = new Stack<>();

    public void push(int node) {
        this.dataStack.push(node);
        if (minStack.isEmpty() || node < minStack.peek()) {
            minStack.push(node);
        } else {
            minStack.push(minStack.peek());
        }
    }

    public void pop() {
        if (!dataStack.isEmpty()) {
            dataStack.pop();
            minStack.pop();
        }
    }

    public int top() {
        return dataStack.peek();
    }

    public int min() {
        return minStack.peek();
    }
}

python:

# -*- coding:utf-8 -*-
class Solution:
    data_stack = []
    min_stack = []

    def push(self, node):
        self.data_stack.append(node)
        if len(self.min_stack) == 0 or node < self.min_stack[-1]:
            self.min_stack.append(node)
        else:
            self.min_stack.append(self.min_stack[-1])

    def pop(self):
        if len(self.data_stack) > 0:
            self.data_stack.pop()
            self.min_stack.pop()

    def top(self):
        return self.data_stack[-1]

    def min(self):
        return self.min_stack[-1]