Stack
You are given a list of eight integer values (23, 20, 90, 45, 75, 24, 30, 48) and consider they are
stored in a stack. You have to find the highest value and get out that value out from this stack.
Finally, stack should be leaved as 23, 20, 45, 75, 24, 30, 48.
Write a program (Java code or pseudo code) to store these values in a stack and get the largest
value out of these values. Assume stack class is already implemented and the implementation of
the stack interface is given as follows. Use stack functions directly in your code.
public interface Stack {
public boolean isEmpty();
public void push(int d);
public int pop();
public int peek();
}
1 Answer
3 years ago by Pulini Tilanka
class MaxStack {
public:
// {val,maxVal. till that point}
vector< pair<int,int> > s;
MaxStack() { }
void push(int val) {
if(s.empty())
s.push_back({val,val});
else
s.push_back({val,max(s.back().second,val)});
}
void pop() {
s.pop_back();
}
int top() {
return s.back().first;
}
int getMin() {
return s.back().second;
}
bool isEmpty(){
return s.size()==0;
}
};
2 years ago by Minato