数据结构——栈的顺序存储

栈的顺序存储实现
栈的顺序存储结构通常由一个一维数组和一个记录栈顶元素位置的变量组成

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

typedef struct SNode
{
int data[MAXSIZE];
int top;
}Stack;

Stack* InitStack();
bool IsFull(Stack*);
bool IsEmpty(Stack*);
bool Push(Stack*, int);
int Pop(Stack*);

int main()
{
Stack* s = InitStack();
printf("是否空:%d\n\n", IsEmpty(s));

int i;
for(i = 1; i < 11; i++)
{
Push(s, i);
}
printf("是否满:%d\n\n", IsFull(s));

Push(s, 11);

for(i = 1; i <= 10; i++)
{
int x = Pop(s);
printf("%d\n", x);
}
printf("是否空:%d\n\n", IsEmpty(s));
Pop(s);

return 0;
}

Stack* InitStack()
{
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
return s;
}

bool IsFull(Stack* s)
{
return s->top == MAXSIZE - 1;
}

bool IsEmpty(Stack* s)
{
return s->top == -1;
}

bool Push(Stack* s, int x)
{
bool ret = true;
if(IsFull(s))
{
printf("栈满\n");
ret = false;
}
else
{
s->data[++(s->top)] = x;
}
return ret;
}

int Pop(Stack* s)
{
if(IsEmpty(s))
{
printf("栈空\n");
// return ERROR; 特殊值标志错误
}
else
{
return s->data[s->top--];
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2020-2021 zhangguoliu
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信