-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstack.c
More file actions
75 lines (61 loc) · 1.2 KB
/
stack.c
File metadata and controls
75 lines (61 loc) · 1.2 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
//
// stack.c
// RegexCompiler
//
// Created by 臻华的Macbook pro on 2018/11/18.
// Copyright © 2018 臻华的Macbook pro. All rights reserved.
//
#include "stack.h"
Stack *InitStack(void)
{
Stack *s = malloc(sizeof(Stack));
s->size = STACK_INIT_SIZE;
s->top = s->base = calloc(sizeof(void *), STACK_INIT_SIZE);
if (!s->base) StackError();
return s;
}
void Push(Stack *s, const void *ele)
{
if (s->top - s->base >= s->size) {
s->base = realloc(s->base, s->size);
if (!s->base) StackError();
s->top = s->base + s->size;
s->size += STACK_INCREMENT;
}
*(s->top++) = ele;
}
void *Pop(Stack *s)
{
if (s->top <= s->base) StackEmpty();
return (void*)*(--s->top);
}
void *GetTop(const Stack *s)
{
if (s->base == s->top) StackEmpty();
return (void*)*(s->top-1);
}
void StackError(void)
{
printf("栈内存分配失败\n");
exit(1);
}
void StackEmpty(void)
{
printf("栈已空\n");
exit(1);
}
void FreeStack(Stack *s)
{
free(s->base);
s->base = NULL;
free(s);
s = NULL;
}
size_t Stack_Size(Stack *s)
{
return s->top - s->base;
}
bool EmptyStack(Stack *s)
{
return s->base == s->top;
}