#include <bits/stdc++.h>
using
namespace
std;
class
Stack {
private
:
int
Max = 5;
int
* arr =
new
int
(Max);
int
minEle = 0;
int
top = 0;
public
:
bool
empty()
{
if
(top <= 0) {
return
true
;
}
else
{
return
false
;
}
}
void
push(
int
x)
{
if
(empty()) {
minEle = x;
arr[top] = x;
top++;
}
else
if
(top == Max) {
Max = 2 * Max;
int
* temp =
new
int
(Max);
for
(
int
i = 0; i < top; i++) {
temp[i] = arr[i];
}
if
(x < minEle) {
temp[top] = 2 * x - minEle;
minEle = x;
top++;
}
else
{
temp[top] = x;
top++;
}
arr = temp;
}
else
{
if
(x < minEle) {
arr[top] = 2 * x - minEle;
top++;
minEle = x;
}
else
{
arr[top] = x;
top++;
}
}
}
void
pop()
{
if
(empty()) {
cout <<
"Underflow"
<< endl;
return
;
}
int
t = arr[top - 1];
if
(t < minEle) {
cout <<
"Popped element : "
<< minEle << endl;
minEle = 2 * minEle - t;
}
else
{
cout <<
"Popped element : "
<< t << endl;
}
top--;
return
;
}
int
peek()
{
if
(empty()) {
cout <<
"Underflow"
<< endl;
return
-1;
}
int
t = arr[top - 1];
if
(t < minEle) {
return
minEle;
}
else
{
return
t;
}
}
int
getMin()
{
if
(empty()) {
cout <<
"Underflow"
<< endl;
return
-1;
}
else
{
return
minEle;
}
}
};
int
main()
{
Stack S;
S.push(10);
S.push(4);
S.push(9);
S.push(6);
S.push(5);
cout <<
"Top Element : "
<< S.peek() << endl;
cout <<
"Minimum Element : "
<< S.getMin() << endl;
S.pop();
S.pop();
S.pop();
S.pop();
cout <<
"Top Element : "
<< S.peek() << endl;
cout <<
"Minimum Element : "
<< S.getMin() << endl;
return
0;
}
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment