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

来源:互联网 发布:美团外卖数据分析2017 编辑:程序博客网 时间:2024/06/11 05:16

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


此题需要设计出一个数据结构,需要满足栈先进后出的特性,还要满足随时可以取出来最小值。决定采用使用数据栈和辅助栈来实现。数据栈和普通栈一样为新的数据结构提供pop(),push()的支持;辅助栈是为了保存历次push时候的最小值,以便以O(1)的复杂度来完成设计


/**
* 测试数据采用剑指Offer面试题21的测试数据
* @author shanzhi
* 本代码的贡献在与用JAVA实现.
* MyStack类为定义的数据结构,自定义了pop(),push(),peek(),min(),print()方法
*/

import java.util.Stack;class MyStack{    public static Stack<Integer> realStack ;    public static Stack<Integer> minSerStack ;    MyStack(){        realStack = new Stack<Integer>();        minSerStack = new Stack<Integer>();    }    public Integer pop(){        if( realStack.isEmpty()){            return null;        }else{            Integer real = realStack.peek();            Integer min = minSerStack.peek();            if( real == min){                minSerStack.pop();            }            return realStack.pop();        }    }    public void push(Integer value){        realStack.push(value);        if( min() == null ){            minSerStack.push(value);        }else{            minSerStack.push(Math.min(value,min()));        }    }    public Integer peek(){        return realStack.peek();    }    public Integer min(){        if( ! minSerStack.isEmpty()){            Integer min = minSerStack.peek();            return min;        }else{            return null;        }    }    public void print(){        System.out.print("\n数据栈是:");        if(!realStack.isEmpty()){            System.out.print(realStack);        }else{            System.out.println("没有值");        }        System.out.print("\n辅助栈是:");        if(!minSerStack.isEmpty()){            System.out.print(minSerStack);        }else{            System.out.println("没有值");        }    }}public class JZ21_StackWithMinFunction {    public static void main(String[] args) {        MyStack ms = new MyStack();        ms.push(3);        ms.push(4);        ms.push(2);        ms.push(1);        ms.print();         ms.pop();        ms.pop();        ms.print();         ms.push(0);        ms.print();    }}
原创粉丝点击