Implementation of Minimum stack
Example 1:
Input: push={10,23,5} ,getminimun ,push={6,3}, getminimum, pop, getminimum
Output: 5,3,5
Approach:
Java
import java.util.Stack;import javafx.util.Pair;@SuppressWarnings("restriction")public class MinimumStack {public static void main(String[] args) {// stack pair to hold the element and the// minimum at the top of stackStack<Pair<Integer, Integer>> stack =new Stack<Pair<Integer, Integer>>();// add element'saddELement(stack, 5);addELement(stack, 23);addELement(stack, 10);// find minimum elementSystem.out.print(findMinimumElement(stack) + " ");// add again element'saddELement(stack, 3);addELement(stack, 6);// find minimumSystem.out.print(findMinimumElement(stack) + " ");removeElement(stack);// find minimumSystem.out.print(findMinimumElement(stack) + " ");}// method for remove element from top of stackprivate static void removeElement(Stack<Pair<Integer,Integer>> stack) {if (!stack.isEmpty())stack.pop();}private static void addELement(Stack<Pair<Integer,Integer>> stack, int value) {int new_min;// if stack is empty then// the minimum element is the given elememtif (stack.isEmpty())new_min = value;// else the minimum element is// the min of stack top and current elementelsenew_min = Math.min(stack.peek().getValue(), value);// push the current element// with the minimum elementstack.add(new Pair<Integer, Integer>(value, new_min));}// method for find minimum value from the stackprivate static int findMinimumElement(Stack<Pair<Integer,Integer>> stack) {// if empty then -1if (stack.isEmpty())return -1;Pair<Integer, Integer> p = stack.peek();return (int) p.getValue();}}
C++
#include <bits/stdc++.h>using namespace std;//function to add the new element//into the stackvoid addElement(stack<pair<int,int>> &st,int value){int new_min;//if stack is empty then//the minimum element is the given//elememtif(st.empty())new_min=value;//else the minimum element is//the min of stack top and current elememtelsenew_min=min(st.top().second,value);//push the current element//with the minimum elementst.push({value,new_min});}//function to remove the//top of the stackvoid removeElement(stack<pair<int,int>> &st){//if not emptyif(!st.empty()){int removed_element=st.top().first;//remove the to element from the stackst.pop();}}//function to find the//minimum element of the stackint findMinimumElement(stack<pair<int,int>> &st){//if stack is empty//return -1if(st.empty())return -1;//else return the minimum element from//the stackelsereturn st.top().second;}int main(){//stack pair to hold the element and the//minimum at the top of stackstack<pair<int,int>> st;addElement(st,10);addElement(st,23);addElement(st,5);//print 5cout<<findMinimumElement(st)<<"\n";addElement(st,6);addElement(st,3);//print 3cout<<findMinimumElement(st)<<"\n";removeElement(st);//print 5cout<<findMinimumElement(st)<<"\n";return 0;}
No comments:
Post a Comment