Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rahulgupta-jsr
Last active May 13, 2018 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahulgupta-jsr/92797e72f138a24226bd37b2af27c0ca to your computer and use it in GitHub Desktop.
Save rahulgupta-jsr/92797e72f138a24226bd37b2af27c0ca to your computer and use it in GitHub Desktop.
Stack with const time get_min() function
#include <cstdlib>
#include <iostream>
#include <stack>
class CustomStack {
public:
void push(int num);
void pop();
int top();
int get_min();
private:
std::stack<int> m_elem;
int m_minval;
};
void CustomStack::push(int num)
{
if (m_elem.empty()) {
m_elem.push(0);
m_minval = num;
}
else {
m_elem.push(num - m_minval);
if (num < m_minval) {
/* updating min val */
m_minval = num;
}
}
}
void CustomStack::pop()
{
int delta = m_elem.top();
m_elem.pop();
if (delta < 0) {
/* IMP: revert to previous minimum */
m_minval -= delta;
}
}
int CustomStack::top()
{
if (m_elem.top() > 0) {
/* return the normalized value */
return m_minval + m_elem.top();
}
else {
return m_minval;
}
}
int CustomStack::get_min()
{
return m_minval;
}
int main()
{
srand(time(NULL));
/* Lets create a stack and push some random values */
CustomStack s;
for (int i = 0; i < 10; i++) {
int num = rand() % 100;
std::cout << "Inserting :" << num << std::endl;
s.push(num);
}
std::cout << std::endl;
std::cout << "Min is " << s.get_min() << std::endl;
s.pop();
s.pop();
s.pop();
s.pop();
std::cout << "After 4 pop(s), min is " << s.get_min() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment