栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

特殊栈(Java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

特殊栈(Java)

题目

实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
 

要求

pop push getMin 时间复杂度都是O(1)

pop push getMin 时间复杂度都是O(1)

代码 
import java.util.Stack;
public class MyStack2 {
    private Stack stackData;
    private Stack stackMin;

    public MyStack2() {
        this.stackData = new Stack();
        this.stackMin = new Stack();
    }

    public void push(int newNum) {
        if (getMin() <= newNum) {
            int value = this.stackMin.peek();
            this.stackMin.push(value);
        } else {
            stackMin.push(newNum);
        }
        this.stackData.push(newNum);
    }

    public Integer pop() {
        if (stackData.isEmpty()) {
            throw new RuntimeException("Your stack is empty");
        }
        stackMin.pop();
        return stackData.pop();
    }

    public Integer getMin() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty");
        }
        return stackMin.peek();
    }

    public static void main(String[] args) {
        MyStack1 stack = new MyStack1();
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(1);
        stack.push(4);
        stack.push(1);
        System.out.println(stack.getMin());

    }
}

//方式二
import java.util.Stack;

public class MyStack1 {
    private Stack stackDate;
    private Stack stackMin;

    public MyStack1() {
        this.stackDate = new Stack();
        this.stackMin = new Stack();
    }

    public void push(int newNum) {
        if (this.stackMin.isEmpty()) {
            stackMin.push(newNum);
        } else {
            //边界限制
            if (getMin() > newNum) {
                this.stackMin.push(newNum);
            }
        }

        this.stackDate.push(newNum);

    }

    public Integer pop() {
        if (stackDate.isEmpty()) {
            throw new RuntimeException("Your stack is empty");
        }
        Integer value = stackDate.pop();
        //判断stackMin 是否需要弹出
        if (value == getMin()) {
            stackMin.pop();
        }
        return value;
    }

    public Integer getMin() {
        if (this.stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty");
        }
        return stackMin.peek();
    }

    public static void main(String[] args) {
        MyStack1 stack = new MyStack1();
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(1);
        stack.push(4);
        stack.push(1);

        System.out.println(stack.getMin());

    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/705054.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号