-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpracticep46_stack_2.cpp
More file actions
83 lines (74 loc) · 1.69 KB
/
practicep46_stack_2.cpp
File metadata and controls
83 lines (74 loc) · 1.69 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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int data){
this->data=data;
this->next=NULL;
}
};
void push(Node* &head,Node* &tail,int data){
cout<<"Pushed "<<data<<endl;
Node* newnode= new Node(data);
if(head==NULL){
head=newnode;
tail=newnode;
return;
};
newnode->next=head;
head=newnode;
};
void pop(Node* &head,Node* &tail){
if(head==NULL){
cout<<"Stack is empty!"<<endl;
return;
};
cout<<"Popped "<<head->data<<endl;
Node *temp=head; //we dont want to delete head directly
head=temp->next;
delete temp; //deleting the last element of the stack
}
void display(Node* &head,Node* &tail){
Node* temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
};
};
int main(){
int choice,data;
Node* head=NULL;
Node* tail=NULL;
while(true){
cout<<"Enter choice: ";
cin>>choice;
if(choice==1){
cout<<"Enter data: ";
cin>>data;
push(head,tail,data);
cout<<"Stack now: ";
display(head,tail);
cout<<endl;
}
else if(choice==2){
pop(head,tail);
cout<<"Stack now: ";
display(head,tail);
cout<<endl;
}
else if(choice==3){
cout<<"Data inside stack: ";
display(head,tail);
cout<<endl;
}
else if(choice==4){
cout<<"Exiting...";
return false; //or break, return 0, false
}
else{
cout<<"Invalid choice! Try again."<<endl;
};
};
}