zoukankan      html  css  js  c++  java
  • Min Stack

    1. Title

    Min Stack

    2. Http address

    https://leetcode.com/problems/min-stack/

    3. The question

    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.

    4 My code(AC)

    •  
       1 public class MinStack {
       2 
       3     // Accepted 
       4     public LinkedList<Integer> stack = new LinkedList<Integer>();
       5     public LinkedList<Integer> min_stack = new LinkedList<Integer>();
       6     
       7       public void push(int x) {
       8           
       9               stack.offerFirst(x);
      10               
      11               if ( min_stack.isEmpty() || x < min_stack.peekFirst()) {
      12                   min_stack.offerFirst(x);
      13               }else{
      14                   min_stack.offerFirst(min_stack.peekFirst());
      15               }
      16       }
      17 
      18      public void pop() {
      19             stack.pollFirst();
      20             min_stack.pollFirst();
      21      }
      22 
      23         public int top() {
      24             return stack.peekFirst();
      25         }
      26 
      27         public int getMin() {
      28                 return min_stack.peekFirst();
      29         }
      30 }
       
     
     
  • 相关阅读:
    考研_数据结构
    快速排序模板
    nginx设置跳转https
    PHP 构造函数
    js scroll事件
    php获取url中的参数
    js 的cookie问题
    yii2关联表
    sql优化之concat/concat_ws/group_concat
    yii2.0 url美化-apache服务器
  • 原文地址:https://www.cnblogs.com/ordili/p/4970062.html
Copyright © 2011-2022 走看看