TheAlgorithms-C-Plus-Plus/data_structure/Stack Using Array.cpp

80 lines
944 B
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-12-24 01:30:49 +08:00
using namespace std;
int *stack;
2019-08-21 10:10:08 +08:00
int top = 0, size;
2017-12-24 01:30:49 +08:00
void push(int x)
{
2019-08-21 10:10:08 +08:00
if (top == size)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nOverflow";
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
stack[top++] = x;
2017-12-24 01:30:49 +08:00
}
}
void pop()
{
2019-08-21 10:10:08 +08:00
if (top == 0)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nUnderflow";
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
cout << "\n"
<< stack[--top] << " deleted";
2017-12-24 01:30:49 +08:00
}
}
void show()
{
for (int i = 0; i < top; i++)
{
2019-08-21 10:10:08 +08:00
cout << stack[i] << "\n";
2017-12-24 01:30:49 +08:00
}
}
void topmost()
{
2019-08-21 10:10:08 +08:00
cout << "\nTopmost element: " << stack[top - 1];
2017-12-24 01:30:49 +08:00
}
int main()
{
2019-08-21 10:10:08 +08:00
cout << "\nEnter Size of stack : ";
cin >> size;
stack = new int[size];
2017-12-24 01:30:49 +08:00
int ch, x;
do
{
2019-08-21 10:10:08 +08:00
cout << "\n1. Push";
cout << "\n2. Pop";
cout << "\n3. Print";
cout << "\n4. Print topmost element:";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "\nInsert : ";
cin >> x;
2017-12-24 01:30:49 +08:00
push(x);
}
2019-08-21 10:10:08 +08:00
else if (ch == 2)
2017-12-24 01:30:49 +08:00
{
pop();
}
2019-08-21 10:10:08 +08:00
else if (ch == 3)
2017-12-24 01:30:49 +08:00
{
show();
}
2019-08-21 10:10:08 +08:00
else if (ch == 4)
{
topmost();
}
} while (ch != 0);
2017-12-24 01:30:49 +08:00
return 0;
}