-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack_using_linked_list.c
172 lines (159 loc) · 2.49 KB
/
Stack_using_linked_list.c
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
//Implement stack using linked list
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *next;
};
struct stack * top = NULL;
struct stack * Push(struct stack *);
struct stack * Pop(struct stack *);
int peek(struct stack *);
int size(struct stack *);
void Display(struct stack *);
int main()
{
int option,val;
printf("******MAIN MENU******");
printf("\n1.Push\n2.Pop\n3.Peek\n4.Size\n5.Display\n6.Exit");
top:
printf("\nYour option:\t");
scanf("%d",&option);
switch(option)
{
case 1:
top = Push(top);
break;
case 2:
top = Pop(top);
break;
case 3:
val = peek(top);
if(val!=-1)
printf("\nValue at the top of stack is:%d",val);
break;
case 4:
val = size(top);
if(val==-1)
{printf("\nStack is empty.");}
else
{printf("\nSize is: %d",val);}
break;
case 5:
Display(top);
break;
case 6:
exit(0);
break;
default:
printf("\nInvalid Input");
break;
}
goto top;
return 0;
}
//--------------------------------------------------------------------------------------
//PUSH
struct stack * Push(struct stack * top)
{
int num;
struct stack *new_node;
new_node = (struct stack*)malloc(sizeof(struct stack));
if(new_node==NULL)
{
printf("\nOut of memory space.");
exit(0);
}
else
{
printf("\nEnter value: ");
scanf("%d",&num);
if(top==NULL)
{
new_node -> data = num;
top = new_node;
new_node -> next =NULL;
}
else
{
new_node -> data = num;
new_node -> next = top;
top = new_node;
}
}
return top;
}
//POP
struct stack * Pop(struct stack * top)
{
int temp=-1;
if(top==NULL)
{
printf("\nLINKED LIST IS EMPTY.");
}
else
{
struct stack *ptr;
ptr = top;
temp = ptr -> data;
top = top -> next;
free(ptr);
printf("\nValue removed from top of stack: %d",temp);
}
return top;
}
//PEEK
int peek(struct stack * top)
{
int temp=-1;
if(top==NULL)
{
printf("\nLINKED LIST IS EMPTY.");
}
else
{
temp = top -> data;
}
return temp;
}
//SIZE
int size(struct stack * top)
{
int count=0;
if(top==NULL)
{
return -1;
}
else
{
struct stack *ptr;
ptr = top;
while(ptr !=NULL)
{
count++;
ptr = ptr -> next;
}
return count;
}
}
//DISPLAY
void Display(struct stack * top)
{
if(top==NULL)
{
printf("\nLINKED LIST IS EMPTY.");
}
else
{
struct stack *ptr;
ptr = top;
while(ptr != NULL)
{
printf("%d " , ptr -> data );
ptr = ptr -> next;
}
}
}