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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef int ElemType;

typedef struct{
ElemType *data;
int top;
}Stack;
//定义栈

Stack* initStack()
{
Stack *s = (Stack*)malloc(sizeof(Stack));
s->data = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
s->top = -1;
return s;
}
//初始化

int isEmpty(Stack *s)
{
if(s->top == -1)
{
printf("Empty.\n");
return 1;
}
else
{
return 0;
}
}
//确认栈是否为空

int push(Stack *s,ElemType e)
{
if(s->top >= MAXSIZE - 1)
{
printf("Full.\n");
return 0;
}
s->top++;
s->data[s->top] = e;
return 1;
}
//压栈

ElemType pop(Stack *s,ElemType *e)
{
if(s->top == -1)
{
printf("Empty.\n");
return 0;
}
*e = s->data[s->top];
s->top--;
return 1;
}
//出栈

int getTop(Stack *s,ElemType *e)
{
if(s->top == -1)
{
printf("Empty.\n");
return 0;
}
*e = s->data[s->top];
return 1;
}
//获取栈顶元素

int main()
{
Stack *s;
s=initStack();
push(s,10);
push(s,20);
push(s,30);
ElemType e;
pop(s,&e);
printf("%d\n", e);
getTop(s, &e);
printf("%d\n", e);
return 0;
}