TheAlgorithms-C-Plus-Plus/Data Structure/Stack Using Linked List.cpp

74 lines
780 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;
struct node
{
int val;
node *next;
};
node *top;
void push(int x)
{
node *n = new node;
2019-08-21 10:10:08 +08:00
n->val = x;
n->next = top;
top = n;
2017-12-24 01:30:49 +08:00
}
void pop()
{
2019-08-21 10:10:08 +08:00
if (top == NULL)
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
{
node *t = top;
2019-08-21 10:10:08 +08:00
cout << "\n"
<< t->val << " deleted";
top = top->next;
2017-12-24 01:30:49 +08:00
delete t;
}
}
void show()
{
2019-08-21 10:10:08 +08:00
node *t = top;
while (t != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << t->val << "\n";
t = t->next;
2017-12-24 01:30:49 +08:00
}
}
int main()
{
int ch, x;
do
{
2019-08-21 10:10:08 +08:00
cout << "\n1. Push";
cout << "\n2. Pop";
cout << "\n3. Print";
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
} while (ch != 0);
2017-12-24 01:30:49 +08:00
return 0;
}