剑指Offer(二十)包含min函数的栈(Java版 )

一、题目描述

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

二、方法分析

import java.util.Stack;

import java.util.*;
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int node) {
        stack1.push(node);
    }  
    public void pop() {
        stack1.pop();
    }
    public int top() {
        return stack1.peek();
    }
    public int min() {
        //先取出第一个元素,将其设为最小值
        int min = stack1.pop();
        //用另外一个栈stack2,保存stack1中的元素
        stack2.push(min);
        int a = 0;
        while(!stack1.isEmpty()){
            //循环取出元素,并判断是否并min小
            a = stack1.pop();
            if( a < min ) min = a;
            //用另外一个栈stack2,保存stack1中的元素
            stack2.push(a);
        }
        //将stack2的元素返还给stack1
        while(!stack2.isEmpty()) stack1.push(stack2.pop());
        //放回最小值
        return min;
    }
}

运行结果:
这里写图片描述

三、方法二分析

public class Solution {
    //定义两个栈
    Stack data=new Stack();
    Stack min=new Stack();

    public void push(int node) {
        //如果min栈为空
        if(min.empty()){
            min.push(node);  //将元素放入名为min栈中
        }else{
            //取出min栈中的最上面的元素
            int top=(int)min.peek();
            //如果要插入node元素小于min栈上面的元素
            if(node<top){
               //就将它放入到min栈
               min.push(node);
            }else{
               //top元素小的话,将top元素放入min栈
               min.push(top);
            }
        }
        //data栈放入元素
        data.push(node);
    }
    public void pop() {
        if(!(data.empty())){
            data.pop();
            min.pop();
        }
    }
    public int top() {
        return (int)data.peek();
    }
    public int min() {
       if(min.empty()){
           return 0;
       }
       return (int)min.peek();    
    }
}

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41835916/article/details/80693442