剑指Offer (java实现)包含min函数的栈

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min,push及pop的时间复杂度都是O(1).

思路:加入一个辅助栈用来存储最小值集合

(这里要注意题目并没有说栈内的元素类型,因此要尽量通用)

在这里插入图片描述
在这里插入图片描述
实现代码如下:

 import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack =new Stack<Integer>();//创建两个栈,一个放入,一个作缓存
        Stack<Integer> stack2 =new Stack<Integer>();
        
        public void push(int node) {
            stack.push(node);
            
        }
        
        public void pop() {
            stack.pop();//pop()函数返回栈顶的元素,并且将该栈顶元素出栈。
        }
        
        public int top() {
            return stack.peek();//peek()函数返回栈顶的元素,但不弹出该栈顶元素。
            
        }
        //以上为栈的定义
        public int min() {
            int min=Integer.MAX_VALUE;
            while(stack.isEmpty()!=true){//栈中非空
                int node=stack.pop();
                if(node<min){
                    min=node;
                }
                stack2.push(node);
            }
            //如果stack为空,则向下执行
            while(stack2.isEmpty()!=true){//栈中非空
                stack.push(stack2.pop());
            }
            return min;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_30242987/article/details/93715529