Skip to content

Commit ca76c7b

Browse files
author
n0r01tk
committed
cpp pgm to implement stack in O(1) time complexity
1 parent 2bb6ea9 commit ca76c7b

File tree

1 file changed

+133
-0
lines changed

1 file changed

+133
-0
lines changed
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
#include <iostream>
2+
#include <stdlib.h>
3+
4+
using namespace std;
5+
6+
/* A simple stack class with
7+
basic stack funtionalities */
8+
class Stack {
9+
private:
10+
static const int max = 100;
11+
int arr[max];
12+
int top;
13+
14+
public:
15+
Stack() { top = -1; }
16+
bool isEmpty();
17+
bool isFull();
18+
int pop();
19+
void push(int x);
20+
};
21+
22+
/* Stack's member method to check
23+
if the stack is iempty */
24+
bool Stack::isEmpty()
25+
{
26+
if (top == -1)
27+
return true;
28+
return false;
29+
}
30+
31+
/* Stack's member method to check
32+
if the stack is full */
33+
bool Stack::isFull()
34+
{
35+
if (top == max - 1)
36+
return true;
37+
return false;
38+
}
39+
40+
/* Stack's member method to remove
41+
an element from it */
42+
int Stack::pop()
43+
{
44+
if (isEmpty()) {
45+
cout << "Stack Underflow";
46+
abort();
47+
}
48+
int x = arr[top];
49+
top--;
50+
return x;
51+
}
52+
53+
/* Stack's member method to insert
54+
an element to it */
55+
void Stack::push(int x)
56+
{
57+
if (isFull()) {
58+
cout << "Stack Overflow";
59+
abort();
60+
}
61+
top++;
62+
arr[top] = x;
63+
}
64+
65+
/* A class that supports all the stack
66+
operations and one additional
67+
operation getMin() that returns the
68+
minimum element from stack at
69+
any time. This class inherits from
70+
the stack class and uses an
71+
auxiliarry stack that holds minimum
72+
elements */
73+
class SpecialStack : public Stack {
74+
Stack min;
75+
76+
public:
77+
int pop();
78+
void push(int x);
79+
int getMin();
80+
};
81+
82+
/* SpecialStack's member method to insert
83+
an element to it. This method
84+
makes sure that the min stack is also
85+
updated with appropriate minimum
86+
values */
87+
void SpecialStack::push(int x)
88+
{
89+
if (isEmpty() == true) {
90+
Stack::push(x);
91+
min.push(x);
92+
}
93+
else {
94+
Stack::push(x);
95+
int y = min.pop();
96+
min.push(y);
97+
if (x < y)
98+
min.push(x);
99+
else
100+
min.push(y);
101+
}
102+
}
103+
104+
/* SpecialStack's member method to
105+
remove an element from it. This method
106+
removes top element from min stack also. */
107+
int SpecialStack::pop()
108+
{
109+
int x = Stack::pop();
110+
min.pop();
111+
return x;
112+
}
113+
114+
/* SpecialStack's member method to get
115+
minimum element from it. */
116+
int SpecialStack::getMin()
117+
{
118+
int x = min.pop();
119+
min.push(x);
120+
return x;
121+
}
122+
123+
int main()
124+
{
125+
SpecialStack s;
126+
s.push(10);
127+
s.push(20);
128+
s.push(30);
129+
cout << s.getMin() << endl;
130+
s.push(5);
131+
cout << s.getMin();
132+
return 0;
133+
}

0 commit comments

Comments
 (0)