一、栈(Stack)的介绍
栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
二、具体1、添加相关头文件
#include <stdio.h>#include <stdlib.h>#include <time.h>
2、定义栈
typedef struct Stack { int *data; int top, size;} Stack;
3、初始化栈
Stack *init(int n) { Stack *s = (Stack *)malloc(sizeof(Stack)); s->data = (int *)malloc(sizeof(int) * n); s->size = n; s->top = -1; return s;}
4、判断是否为空及查看栈顶
int empty(Stack *s) { return s->top == -1;}int top(Stack *s) { if (empty(s)) return 0; return s->data[s->top];}
5、插入
int push(Stack *s, int val) { if (s == NULL) return 0; if (s->top + 1 == s->size) return 0; s->top += 1; s->data[s->top] = val; return 1;}
6、出栈操作
int pop(Stack *s) { if (s == NULL) return 0; if (empty(s)) return 0; s->top -= 1; return 1;}
7、清空
void clear(Stack *s) { if (s == NULL) return ; free(s->data); free(s); return ;}
8、输出栈
void output(Stack *s) { printf("stack(%d) = [", s->top + 1); for (int i = s->top; i >= 0; i--) { printf(" %d", s->data[i]); } printf("]
"); return ;}
9、主函数(随机进行20次随机测试)
int main() { srand(time(0)); #define MAX_OP 20 Stack *s = init(MAX_OP); for (int i = 0; i < MAX_OP; i++) { int op = rand() % 2, val = rand() % 100; switch (op) { case 0: { printf("push %d to stack = %d
", val, push(s, val)); } break; case 1: { printf("pop %d from stack = %d
", top(s), pop(s)); } } output(s); } return 0;}
10、完整代码
#include <stdio.h>#include <stdlib.h>#include <time.h>typedef struct Stack { int *data; int top, size;} Stack;Stack *init(int n) { Stack *s = (Stack *)malloc(sizeof(Stack)); s->data = (int *)malloc(sizeof(int) * n); s->size = n; s->top = -1; return s;}int empty(Stack *s) { return s->top == -1;}int top(Stack *s) { if (empty(s)) return 0; return s->data[s->top];}int push(Stack *s, int val) { if (s == NULL) return 0; if (s->top + 1 == s->size) return 0; s->top += 1; s->data[s->top] = val; 西藏干部培训学校 www.swuplganxun.com return 1;}int pop(Stack *s) { if (s == NULL) return 0; if (empty(s)) return 0; s->top -= 1; return 1;}void clear(Stack *s) { if (s == NULL) return ; free(s->data); free(s); return ;}void output(Stack *s) { printf("stack(%d) = [", s->top + 1); for (int i = s->top; i >= 0; i--) { printf(" %d", s->data[i]); } printf("]
"); return ;}int main() { srand(time(0)); #define MAX_OP 20 Stack *s = init(MAX_OP); for (int i = 0; i < MAX_OP; i++) { int op = rand() % 2, val = rand() % 100; switch (op) { case 0: { printf("push %d to stack = %d
", val, push(s, val)); } break; case 1: { printf("pop %d from stack = %d
", top(s), pop(s)); } } output(s); } return 0;}
三、栈的基本概念
要搞清楚这个概念,首先要明白”栈“原来的意思,如此才能把握本质。栈,存储货物或供旅客住宿的地方,可引申为仓库、中转站,所以引入到计算机领域里,就是指数据暂时存储的地方,所以才有进栈、出栈的说法。