数据结构顺序栈

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
#include<stdio.h>
#include<stdlib.h>
#define OK 1 //通过
#define ERROR 0 //错误
#define OVERFLOW -2 //堆栈溢出
#define MAXSIZE 50 //容量
typedef int Status; //函数类型,其值为状态码
typedef char ElemType; //抽象数据类型
//顺序结构储存
typedef struct
{
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
typedef enum
{
f,t
}Bool;
//初始化
Status initStack(SqStack* S)
{
S->base = new ElemType[MAXSIZE];
if (!S->base)
{
exit(OVERFLOW);
}
S->top = S->base;
S->stacksize = MAXSIZE;
return OK;
}
//判空
Bool isEmpty(SqStack* S)
{
return S->base == S->top ? t : f;
}
//长度
int getLength(SqStack* S)
{
return S->top - S->base;
}
//入栈
Status pushElem(SqStack* S,ElemType e)
{
if (getLength(S) == S->stacksize)return ERROR;
*(S->top) = e;
S->top++;
return OK;
}
//出栈
ElemType popElem(SqStack* S)
{
if (isEmpty(S))return NULL;
S->top--;
return *(S->top);
}
//取栈顶
ElemType getTop(SqStack* S)
{
if (!isEmpty(S))return *(S->top - 1);
return NULL;
}
int main(void)
{
SqStack* S = new SqStack;
printf("初始化-----------%s\n", initStack(S) == OK ? "成功" : "失败");
printf("是否为空----------%s\n", isEmpty(S) ? "空" : "不空");
char* str = "https://github.com/pengxiandyou";
printf("开始入栈\n");
for (int i = _mbstrlen(str)-1; i >= 0; --i)
{
printf("入栈-----------%s--------长度 %d\n", pushElem(S, str[i])==OK?"成功":"失败",getLength(S));
}
printf("是否为空----------%s\n",isEmpty(S) ? "空" : "不空");
printf("栈顶为---------%c\n", getTop(S));
printf("开始出栈\n");
for (int i = 31- 1; i >= 0; --i)
{
printf("%c",popElem(S) );
}

printf("\n");
system("pause");
return 0;
}