-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackArray1.c
96 lines (87 loc) · 1.55 KB
/
stackArray1.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
#include <stdio.h>
#include <stdlib.h>
#include<limits.h>
struct stack
{
int top;
int capacity;
int *array;
};
struct stack *createStack(int capacity)
{
struct stack *s=malloc(sizeof(struct stack));
if(!s)
return NULL;
s->capacity=capacity;
s->top=-1;
s->array=malloc(s->capacity*sizeof(int));
if(!s->array)
return NULL;
return s;
}
int isEmpty(struct stack *s)
{
return (s->top==-1);
}
int size(struct stack *s)
{
return (s->top+1);
}
int isFull(struct stack*s)
{
return (s->top==s->capacity-1);
}
void push(struct stack *s,int data)
{
if(isFull(s))
printf("Stack Overflow\n");
else
s->array[++s->top]=data;
}
int pop(struct stack*s)
{
if(isEmpty(s))
{
printf ("Stack is empty\n");
return INT_MIN;
}
else
return (s->array[s->top--]);
}
int peek(struct stack*s)
{
if(isEmpty(s))
{
printf ("Stack is empty\n");
return INT_MIN;
}
else
return (s->array[s->top]);
}
void delete(struct stack*s)
{
if(s)
{
if(s->array)
free(s->array);
free(s);
}
}
int main ()
{
int i=0,capacity=15;
//creates a stack of capacity of 15
struct stack *stk=createStack(capacity);
for(i=0;i <=capacity;i++)
push(stk,i);
printf ("Top element is %d\n", peek(stk));
printf ("Stack size is %d\n", size(stk));
for(i=0;i<capacity-1;i++)
printf ("Popped element is %d\n",pop(stk));
if (isEmpty(stk))
printf ("Stack is empty\n");
else
printf ("Stack is not empty");
delete(stk);
return 0;
}