c语言栈的实现以及操作

此文章包含了栈的结构体实现,单数据类型实现,以及清空,判空,入栈,出栈,求栈顶元素的实现 栈是一个非常简单的数据结构 栈本身就相当于一摞盘子,每个数据就是一个盘子,每次你只能把盘子放在最上面或者拿走最上面的盘子 实现起来也非常容易,用数组来模拟这堆盘子 那么我们如果有一个索引TOP时刻指向最上面的那个盘子,栈不就实现了么? 第一段是单数据类型的代码

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 110//栈的最大值
typedef int elem;    //方便修改数据类型
typedef struct{
int top; ///栈顶的索引
elem index[maxn];
}Stack;
Stack stack; ///为了方便这里直接定义全局变量了,用局部变量的话在每个函数加上取地址符和声明就行了
void stack_pop(){ ///元素出栈,此函数无返回值
stack.top--;
}
void stack_push(elem buf){ ///元素入栈
stack.index[++stack.top] = buf;
}
int stack_empty(){///判空,如果栈为空的话返回1,否则返回0
return stack.top == -1;
}

void stack_clear(){ ///清空栈
stack.top = -1;
}

int stack_size(){ ///求栈内元素数
return stack.top+1;
}
elem stack_top(){ ///返回栈顶元素
return stack.index[stack.top];
}

int main()
{
stack_clear();///初始化栈
elem buf;
buf = 10;
stack_push(buf);
printf("%d\n",stack_top());
printf("%d\n",stack_empty());
printf("%d\n",stack_size());
stack_pop();
printf("%d\n",stack_size());
return 0;
}


下面是结构体栈的实现,和上面的基本一样,只修改了部分代码,添加了一个可以糅合数据类型的结构体数组elem

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 11

typedef struct {
int n;
char str[maxn];
}elem; ///要存用栈储的数据类型

typedef struct{
int top; ///栈顶的索引
elem index[maxn];
}Stack;
Stack stack; ///为了方便这里直接定义全局变量了,用局部变量的话加上取地址符和声明就行了
void stack_pop(){ ///元素出栈,此函数无返回值
stack.top--;
}
void stack_push(elem buf){ ///元素入栈
stack.index[++stack.top].n = buf.n;
strcpy(stack.index[stack.top].str,buf.str);
}
int stack_empty(){///判空,如果栈为空的话返回1,否则返回0
return stack.top == -1;
}

void stack_clear(){ ///清空栈
stack.top = -1;
}

int stack_size(){ ///求栈内元素数
return stack.top+1;
}
elem stack_top(){ ///返回栈顶元素
return stack.index[stack.top];
}

int main()
{
stack_clear();
elem buf;
buf.n = 1;
strcpy(buf.str,"abc");
stack_push(buf);
printf("%d %s\n",stack_top().n,stack_top().str);
printf("%d\n",stack_empty());
printf("%d\n",stack_size());
stack_pop();
printf("%d\n",stack_size());
return 0;
}

觉得文章不错的话可以请我喝一杯茶哟~
  • 本文作者: bestsort
  • 本文链接: https://bestsort.cn/2019/04/21/56/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-SA 许可协议。转载请注明出处!并保留本声明。感谢您的阅读和支持!
-------------本文结束感谢您的阅读-------------