Min Stack 实现一个最小栈

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.

  • getMin() -- Retrieve the minimum element in the stack.
转载出处:http://blog.csdn.net/ljiabin/article/details/40982153
class Stack<E> extends Vector<E> 
Vector类也是基于数组实现的队列,代码与ArrayList非常相似,只不过在可能发生线程安全的方法上加上了Synchorized关键字,使得其执行的效率相比ArrayList就低了。由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的。Vector类可以实现可增长的对象数组。与数组一样,它包含可以使用整数索引进行访问的组件。但是,Vector 的大小可以根据需要增大或缩小,以适应创建 Vector 后进行添加或移除项的操作。
【用Java内置的栈实现】
class MinStack {
    private Stack<Integer> stack=new Stack<Integer>();  
 //class Stack<E> extends Vector<E> 
    private Stack<Integer> minStack=new Stack<Integer>();
    public void push(int x) {
        if(minStack.isEmpty() || x<=minStack.peek())
            minStack.push(x);
        stack.push(x);
    }

    public void pop() {
        if(minStack.peek().equals(stack.peek()))
            minStack.pop();
        stack.pop();
    }

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

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


【不用内置栈的实现】感觉leetcode测试集还有其他设置的不太完整缜密,但是大体思路对就好了
  1. class MinStack {  
  2.     Node top = null;  
  3.   
  4.     public void push(int x) {  
  5.         if (top == null) {  
  6.             top = new Node(x);  
  7.             top.min = x;  
  8.         } else {  
  9.             Node temp = new Node(x);  
  10.             temp.next = top;  
  11.             top = temp;  
  12.             top.min = Math.min(top.next.min, x);  
  13.         }  
  14.     }  
  15.   
  16.     public void pop() {  
  17.         top = top.next; 
  18.     }  
  19.   
  20.     public int top() {  
  21.         return top.val;  
  22.     }  
  23.   
  24.     public int getMin() {  
  25.         return top.min;  
  26.     }  
  27. }  
  28.   
  29. class Node {   //自定义了一个Node class
  30.     int val;  
  31.     int min;  
  32.     Node next;  
  33.   
  34.     public Node(int val) {  
  35.         this.val = val;  
  36.     }  
  37. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值