-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_array.c
More file actions
88 lines (77 loc) · 1.38 KB
/
Copy pathstack_array.c
File metadata and controls
88 lines (77 loc) · 1.38 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
#include <stdio.h>
#include <stdlib.h>
typedef struct stack
{
int *arr;
int size;
int cap;
} stack;
// functions:
stack *init_stack(int cap);
void push(stack *s, int val);
int pop(stack *s);
void free_stack(stack *s);
int null_check(stack *s);
void print_stack(stack *s);
stack *init_stack(int cap)
{
stack *newstack = (stack *)malloc(sizeof(stack));
newstack->arr = (int *)malloc(cap * sizeof(int));
newstack->cap = cap;
newstack->size = 0;
return newstack;
}
void push(stack *s, int val)
{
if (null_check(s) != 0)
return;
if (s->size == s->cap)
{
printf("Stack is full\n");
return;
}
s->arr[s->size] = val;
s->size++;
}
int pop(stack *s)
{
if (null_check(s) != 0)
return -1;
int temp = s->arr[--s->size];
return temp;
}
void free_stack(stack *s)
{
if (null_check(s) != 0)
return;
for (int i = 0; i < s->size; i++)
free(&s->arr[i]);
free(s);
}
int null_check(stack *s)
{
if (s == NULL)
{
printf("Stack does not exist\n");
return 1;
}
return 0;
}
void print_stack(stack *s)
{
if (null_check(s) != 0)
return;
for (int i = 0; i < s->size; i++)
printf("%d ", s->arr[i]);
}
int main()
{
stack *s = init_stack(10);
push(s, 2);
push(s, 5);
pop(s);
push(s, 7);
print_stack(s);
return 0;
}
// lec