顺序表实现栈
以下为数据结构作业
如有错误,请指出,谢谢!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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *s)
{
s->base = (SElemType *)malloc(INIT_SIZE * sizeof(SElemType));
if(!s->base)
{
puts("存储空间分配失败!");
return Error;
}
s->top = s->base;
s->stacksize = INIT_SIZE;
return Ok;
}
Status ClearStack(SqStack *s)
{
s->top = s->base;
return Ok;
}
Status StackEmpty(SqStack *s)
{
if(s->top == s->base)
return True;
else return False;
}
Status Destroy(SqStack *s)
{
free(s->base);
s->base = NULL;
s->top = NULL;
s->stacksize=0;
return Ok;
}
Status GetTop(SqStack *s, SElemType &e)
{
if(s->top == s->base)return Error;
e = *(s->top - 1);
return Ok;
}
Status Push(SqStack *s, SElemType e)
{
if(s->top - s->base >= s->stacksize)
{
s->base = (SElemType *)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(SElemType));
if(!s->base)
{
puts("存储空间分配失败!");
return Error;
}
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREMENT;
}
*s->top++ = e;
return Ok;
}
Status Pop(SqStack *s, SElemType *e)
{
if(s->top == s->base)return Error;
--s->top;
*e = *(s->top);
return Ok;
}
Status StackTraverse(SqStack *s,Status(*visit)(SElemType))
{
SElemType *b = s->base;
SElemType *t = s->top;
while(t > b)visit(*b++);
printf("\n");
return Ok;
}
Status visit(SElemType c)
{
printf("%d ",c);
return Ok;
}
void stack_insert(SqStack *s)
{
int n;
puts("请输入要进栈的个数:");
scanf("%d", &n);
printf("请输入%d个数依次入栈\n",n);
while(n--)
{
int m;
scanf("%d", &m);
Push(s, m);
}
}
int main()
{
int n;
SqStack a;
SqStack *s = &a;
SElemType e;
InitStack(s);
stack_insert(s);
StackTraverse(s, visit);
printf("输入1入栈,输入2出栈,输入0退出!\n");
while(scanf("%d",&n)!=EOF)
{
if(n==1)stack_insert(s);
else if(n==2)
{
if(StackEmpty(s))printf("栈为空!\n");
else
{
Pop(s, &e);
printf("出栈的元素是:%d\n", e);
}
}
else break;
StackTraverse(s, visit);
}
Destroy(s);
return 0;
}