Implementation of Maximum stack
Example 1:
Input: push={10,23,5} ,getmaximum ,push={6,123}, getmaximum, pop, getmaximum
Output: 5,3,5
Approach:
Java
import java.util.Stack;import javafx.util.Pair;@SuppressWarnings("restriction")public class MaximumStack {public static void main(String[] args) {// stack pair to hold the element and the// maximum 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 maximum elementSystem.out.print(findMaximumElement(stack) + " ");// add again element'saddELement(stack, 33);addELement(stack, 6);// find maximumSystem.out.print(findMaximumElement(stack) + " ");removeElement(stack);// find maximumSystem.out.print(findMaximumElement(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 maximum element is the given elememtif (stack.isEmpty())new_min = value;// else the maximum element is// the min of stack top and current elementelsenew_min = Math.max(stack.peek().getValue(), value);// push the current element// with the maximum elementstack.add(new Pair<Integer, Integer>(value, new_min));}// method for find maximum value from the stackprivate static int findMaximumElement(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_max;//if stack is empty then//the maximum element is the given//elememtif(st.empty())new_max=value;//else the maximum element is//the max of stack top and current elememtelsenew_max=max(st.top().second,value);//push the current element//with the maximum elementst.push({value,new_max});}//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 top element from the stackst.pop();}}//function to find the//maximum element of the stackint findMaximumElement(stack<pair<int,int>> &st){//if stack is empty//return -1if(st.empty())return -1;//else return the maximum element from//the stackelsereturn st.top().second;}int main(){//stack pair to hold the element and the//maximum at the top of stackstack<pair<int,int>> st;addElement(st,10);addElement(st,23);addElement(st,5);//print 23cout<<findMaximumElement(st)<<"\n";addElement(st,6);addElement(st,123);//print 123cout<<findMaximumElement(st)<<"\n";removeElement(st);//print 23cout<<findMaximumElement(st)<<"\n";return 0;}
No comments:
Post a Comment