-
Notifications
You must be signed in to change notification settings - Fork 0
/
1. Implementation of stack using array
128 lines (112 loc) · 2.33 KB
/
1. Implementation of stack using array
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
/**********************************************************************************************************
TITLE: Implementation of Stack using Array.
**********************************************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define SIZE 10
//Structure declaration
typedef struct
{
float a[SIZE]; //stack of floats
int tos;
}Stack;
int isEmpty(Stack *p)
{
if ((p->tos)== -1)//checks if stack is empty
return (1);
else
return (0);
}
int isFull(Stack *p)
{
if ((p->tos)==SIZE-1)//checks if stack is full
return (1);
else
return (0);
}
//Push Function
void push (Stack *p, float x)
{
if (isFull(p))//if stack is full
{
printf("Stack is overflown\n");
exit(1);
}
else
{
p->tos++;//increment tos
printf("The pushed element is %f\n",x);
p->a[p->tos]=x;//adding element to the top of the stack
}
}
//Pop Function
float pop(Stack *p)
{
if (isEmpty(p))//if stack is full
{
printf("Stack is empty\n");
exit(1);
}
else
{
return(p->a[p->tos--]);//removing element from the top of the stack
}
}
//Peek function
float peek(Stack s)
{
return s.a[s.tos]; //return top element of stack
}
//Display function
void display(Stack s)
{
int i;
for(i = s.tos; i>=0 ; i--)
{
printf("%f\t",s.a[i]);
}
}
//No.of elements in the stack
int size(Stack *p)
{
printf("%d",p->tos+1);//index of top of the stack + 1
}
//Main starts
int main()
{
Stack s1; //s1 is variable of type stack
float x,data;
int option;
s1.tos = -1; //top of stack initialized to -1
do
{
printf("\nEnter the choice 1.Push 2.Pop 3.Peek 4.Display 5.No.of elements in the stack\n");
scanf("%d",&option);
switch(option)
{
case 1:
printf("Enter the element to push\n");
scanf("%f",&x);
push(&s1,x);
break;
case 2:
data = pop(&s1);
printf("\nThe popped element is %f\n",data);
break;
case 3:
printf("The top element is %f\n",peek(s1));
break;
case 4:
printf("\nThe stack contents are :\n");
display(s1);
break;
case 5:
printf("\nNo. of elements in the stack:\n");
size(&s1);
break;
case 6:
exit(0); //exit from program with exit status 0
}
}while(1);//while always true
return 0;
}