-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using Linked List.cpp
More file actions
98 lines (98 loc) · 1.98 KB
/
Stack using Linked List.cpp
File metadata and controls
98 lines (98 loc) · 1.98 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
96
97
98
#include <iostream>
using namespace std;
int size=5; //Size will be compared in every function so defining it globally
struct node{ //will be used as node of a linked list
int data;
node *next;
};
void push(node** head){
int c=0; //c will count no. of nodes in linked link
node *temp=*head;
while(temp!=0)
{
temp=temp->next;
c++;
}//c will have count of number of nodes
if(c==size) //if nodes==size i.e linked list is full
cout<<"\n\t!!! STACK OVERFLOW !!!";
else //adding nodes @ start from head
{
node *newnode=new node();
cout<<"\nEnter data ";cin>>newnode->data;
newnode->next=*head;
*head=newnode;
cout<<"\n"<<newnode->data <<" is added to stack ";
}
}
void pop(node** head){
int c=0; //c will count no. of nodes in linked link
node *temp=*head;
while(temp!=0)
{
temp=temp->next;
c++;
} //c will have count of number of nodes .
if(c==0) //if linked list is empty.
cout<<"\n\t!!! STACK UNDERFLOW !!!";
else //node will be deleted from start i.e head
{
node *t=*head;
cout<<"\n"<<t->data<<" is deleted";
*head=t->next;
delete t;
}
}
void peek(node** head){ //prints top element i.e Element at Head
int c=1;
node *temp=*head;
while(temp->next!=0)
{
temp=temp->next;
c++;
}
if(c==1)
cout<<"\n\t!!! STACK UNDERFLOW !!!";
else
{
node *t=*head;
cout<<"\nTop Element : "<<t->data;
}
}
void display(node** head){
int c=1;
node *temp=*head;
while(temp->next!=0)
{
temp=temp->next;
c++;
}
if(c==1)
cout<<"\n\t!!! STACK UNDERFLOW !!!";
else
{
node *t=*head;
cout<<"\nSTACK IS : ";
while(t!=0)
{
cout<<"\n"<<t->data;
t=t->next;
}
}
}
int main(){
node *head=0;
int choice;
do{
cout<<"\n~~~ MENU ~~~\n1.PUSH\t2.POP\t3.Peek\t4.Display\t5.Exit\n ";
cin>>choice;
switch(choice)
{
case 1:push(&head);break;
case 2:pop(&head);break;
case 3:peek(&head);break;
case 4:display(&head);break;
case 5:cout<<"\n~~~ THANK YOU ~~~";break;
default:cout<<"\nInvalid choic try again ";
}
}while(choice!=5);
}