-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathstack.c
88 lines (76 loc) · 1.43 KB
/
stack.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
#include "stack.h"
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define T Stack_T
typedef struct elem
{
void *val;
struct elem *next;
} elem_t;
struct T
{
int count;
elem_t *head;
};
/* Initial stack */
T Stack_init(void)
{
T stack;
stack = (T)malloc(sizeof(T));
stack->count = 0;
stack->head = NULL;
return stack;
}
/* Check empty stack*/
int Stack_empty(T stack)
{
assert(stack);
return stack->count == 0;
}
/* Return size of the stack */
int Stack_size(T stack)
{
assert(stack);
return stack->count;
}
/* Push an element into the stack */
void Stack_push(T stack, void *val)
{
elem_t *t;
assert(stack);
t = (elem_t *)malloc(sizeof(elem_t));
t->val = val;
t->next = stack->head;
stack->head = t;
stack->count++;
}
/* Pop an element out of the stack */
void *Stack_pop(T stack)
{
void *val;
elem_t *t;
assert(stack);
assert(stack->count > 0);
t = stack->head;
stack->head = t->next;
stack->count--;
val = t->val;
free(t);
return val;
}
/* Print all elements in the stack */
void Stack_print(Stack_T stack)
{
assert(stack);
int i, size = Stack_size(stack);
elem_t *current_elem = stack->head;
printf("Stack [Top --- Bottom]: ");
for (i = 0; i < size; ++i)
{
printf("%p ", (int *)current_elem->val);
current_elem = current_elem->next;
}
printf("\n");
}