1 Stack Min Would Design Stack Addition Push Pop Function Min Returns Minimum Element Push Q37267130

1) Stack Min: How would you design a stack which, in addition topush and pop, has a function min which returns the minimum element?Push, pop and min should all operate in 0(1) time. Please code theabove question in JAVA.


Answer


CODE

import java.util.Stack;

public class MyStack

{

Stack<Integer> s;

Integer minEle;

// Constructor

MyStack() { s = new Stack<Integer>(); }

// Prints minimum element of MyStack

void getMin()

{

// Get the minimum number in the entire stack

if (s.isEmpty())

System.out.println(“Stack is empty”);

// variable minEle stores the minimum element

// in the stack.

else

System.out.println(“Minimum Element in the ” +

” stack is: ” + minEle);

}

// prints top element of MyStack

void peek()

{

if (s.isEmpty())

{

System.out.println(“Stack is empty “);

return;

}

Integer t

OR
OR

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.