forked from Shailendra-Java/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLinkedList.cpp
More file actions
95 lines (90 loc) · 2.14 KB
/
StackUsingLinkedList.cpp
File metadata and controls
95 lines (90 loc) · 2.14 KB
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
91
92
93
94
95
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
class StackUsingLinkedList{
public:
Node *top;
StackUsingLinkedList(){
top = NULL;
}
Node* createNode(int num){
Node *temp = new Node;
if(temp == NULL)
cout<<"Node creation failed"<<endl;
else{
temp->data = num;
temp->next = NULL;
return temp;
}
}
void push(){
int num;
Node *ptr;
cout<<"Enter a number"<<endl;
cin>>num;
ptr = createNode(num);
if(top == NULL){
top = ptr;
cout<<"First "<<top->data<<" element pushed"<<endl;
}
else{
ptr->next = top;
top = ptr;
cout<<"Element "<<ptr->data<<" pushed in stack"<<endl;
}
}
void pop(){
Node *temp;
if(top == NULL)
cout<<"Stack Underflow"<<endl;
else{
temp = top;
top = top->next;
cout<<"Element"<<temp->data<<" popped from stack"<<endl;
delete(temp);
}
}
void display(){
Node *temp;
temp = top;
if(top == NULL)
cout<<"Stack Underflow"<<endl;
else{
while(temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
}
};
int main(){
StackUsingLinkedList sul;
int opn;
char ch;
do{
cout<<"1 => Push\n2 => Pop\n3 => Display"<<endl;
cout<<"Enter your choice"<<endl;
cin>>opn;
switch(opn){
case 1:
sul.push();
break;
case 2:
sul.pop();
break;
case 3:
sul.display();
break;
default:
cout<<"An invalid choice!"<<endl;
}
cout<<"Do you want to continue(y/n)"<<endl;
cin>>ch;
}while(ch == 'y' || ch == 'Y');
return 0;
}