Problem Description:
Defines the data structure of the stack, requiring the addition of a min function to get the smallest element of the stack.
The time complexity required for the function min, push, and Pop is O (1).
Double Space Implementation:
Save 2 stacks, each of which is the element and the current minimum value.
Compact Space Implementation:
?
Code implementation:
package oschina.mianshi;/** * @project: oschina * @filename: it2.java * @version: 0.10 * @author: jm han * @date: 17:08 2015/10/20 * @comment: test purpose * @result: */import java.util.stack;import static tool.util.*;class MinStack{ Stack<Integer> stacks, Mins; minstack () { stacks = new stack< Integer> (); mins = new stack<integer> () ; } void push (integer x) { Stacks.push (x); //<= instead of < is for repeating elements if (Mins.isempty () | | x <= mins.peek ()) mins.push (x); } void pop () { integer x = stacks.pop (); if (X == mins.peek ()) mins.pop (); } integer peek () { return stacks.peek (); } integer getmin () { return mins.peek (); }}public class it2 { public static void main (String[] args) { minstack minstack = new minstack (); Minstack.push (6); minstack.push (2); Minstack.push (3); minstack.push (1); Minstack.push (1); &nbsP; minstack.push (5); minstack.push (8); system.out.println ("min value: " + minstack.getmin ()); minstack.pop (); minstack.pop (); minstack.pop (); minstack.pop (); system.out.println ("min value: " + minstack.getmin ()); }}
Output:
Min Value:1min value:2
IT company 100-design stack with min function