-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack implementation using Linked List
90 lines (83 loc) · 1.87 KB
/
Stack implementation using Linked List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
using namespace std;
//Node structure created
struct Node
{
int data;
struct Node *next;
};
struct Node* top = NULL; //Top initialized as NULL, initially empty
void push(int a) // To add elements to the stack
{
struct Node* newnode = new Node();
newnode->data = a;
newnode->next = top;
top = newnode;
}
void pop() // To delete elements from the stack
{
if(top==NULL)
{
cout<<"Stack is already empty!..."<<endl;
}
else
{
cout<<"The popped element:"<< top->data<<endl;
top = top->next;
}
}
void display() // To display elements of the stack
{
struct Node* temp;
if(top==NULL)
{
cout<<"Stack is empty!";
}
else
{
temp = top;
cout<<"Elements are:";
while (temp!=NULL)
{
cout<< temp->data <<"->";
temp = temp->next;
}
}
cout<<endl;
}
//Main program
int main()
{
int c, a;
cout<<"Options are:"<<endl;
cout<<"1. Push 2. Pop 3. Display 4.Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>c;
switch(c) //switch case to implement user choice based operation implementation
{
case 1: {
cout<<"Enter value:"<<endl;
cin>>a;
push(a);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exiting the program....."<<endl;
break;
}
default:{
cout<<"Wrong Choice"<<endl;
}
}
}while(c!=4); //exit condition
return 0;
}