-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
59 lines (50 loc) · 959 Bytes
/
stack.c
File metadata and controls
59 lines (50 loc) · 959 Bytes
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
/********************
* int 类型的stack
*
* ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct{
int *elems;
int index;
int alloclength;
} stack;
void stackNew(stack *s)
{
s->index = 0;
s->alloclength = 4;
s->elems = (int *)malloc(4 * sizeof(int));
assert(s->elems != NULL);
}
void stackDispose(stack *s)
{
free(s->elems);
}
void stackPush(stack *s, int value)
{
if(s->index ==s->alloclength)
{
s->alloclength *= 2;
s->elems = realloc(s->elems,s->alloclength * sizeof(int));
assert(s->elems != NULL);
}
s->elems[s->index] = value;
s->index ++;
}
int stackPop(stack *s)
{
assert(s->alloclength > 0);
s->index --;
return s->elems[s->index];
}
int main()
{
stack s;
stackNew(&s);
for(int i = 0; i < 10; i ++)
stackPush(&s, i);
printf("%d\n", stackPop(&s));
return 0;
}