用链表实现一个栈
发布日期:2021-06-30 18:42:38
浏览次数:2
分类:技术文章
本文共 2457 字,大约阅读时间需要 8 分钟。
#include#include typedef int ElementType; /*栈元素类型*/#define SUCCESS 0#define FAILURE -1/*定义栈结构*/typedef struct StackInfo{ ElementType value; /*栈存储的数据*/ struct StackInfo *next; /*指向栈的下一个元素*/}StackInfo_st;/*函数声明*/StackInfo_st *createStack(void);int stack_push(StackInfo_st *s,ElementType value);int stack_pop(StackInfo_st *s,ElementType *value);int stack_top(StackInfo_st *s,ElementType *value);int stack_is_empty(StackInfo_st *s);/*创建栈,外部释放内存*/StackInfo_st *createStack(void){ StackInfo_st *stack = (StackInfo_st *)malloc(sizeof(StackInfo_st)); if(NULL == stack) { printf("malloc failed\n"); return NULL; } stack->next = NULL; return stack;}/*入栈,0表示成,非0表示出错*/int stack_push(StackInfo_st *s,ElementType value){ StackInfo_st *temp = (StackInfo_st *)malloc(sizeof(StackInfo_st)); if(NULL == temp) { printf("malloc failed\n"); return FAILURE; } /*将新的节点添加s->next前,使得s->next永远指向栈顶*/ temp->value = value; temp->next = s->next;/*这一句是指向栈头部,实际上不用也没有问题*/ s->next = temp; return SUCCESS;}/*出栈*/int stack_pop(StackInfo_st *s,ElementType *value){ /*首先判断栈是否为空*/ if(stack_is_empty(s)) return FAILURE; /*找出栈顶元素*/ *value = s->next->value; /*保存等下需要free的指针*/ StackInfo_st *temp = s->next; /*更换栈顶的位置*/ s->next = s->next->next; /*释放栈顶节点内存*/ if(temp!=NULL)/*先判断指针是否为空*/ free(temp); temp = NULL; return SUCCESS;}/*访问栈顶元素*/int stack_top(StackInfo_st *s,ElementType *value){ /*首先判断栈是否为空*/ if(stack_is_empty(s)) return FAILURE; *value = s->next->value; return SUCCESS;}/*判断栈是否为空,空返回1,未空返回0*/int stack_is_empty(StackInfo_st *s){ /*栈顶指针为空,则栈为空*/ return s->next == NULL;}int main(void){ /*创建栈*/ StackInfo_st *stack = createStack(); /*如果栈为空,则压入元素1*/ if(stack_is_empty(stack)) { int i = 0; for(i = 0 ;i< 23;i++) { printf("push value %d\n",i); stack_push(stack,i); } } /*访问栈顶元素*/ int topVal; stack_top(stack, &topVal); printf("top value %d\n",topVal); /*出栈*/ int tm = 0; for(tm = 0;tm<25;tm++) { int popVal; stack_pop(stack, &popVal); printf("pop value %d %d\n",tm,popVal); } int i = 0; while(SUCCESS == stack_push(stack,i) && i < 5) { i++; } printf("top if stack value is %d\n",stack->next->value); /*最后记得将栈内存都释放,可自己尝试实现*/ return 0;}
转载地址:https://linus.blog.csdn.net/article/details/102336852 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月13日 03时16分09秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【深度学习笔记】循环神经网络和递归神经网络区别
2019-04-30
【学习笔记】英文科技论文常见英语句式积累
2019-04-30
【深度学习笔记】PixelShuffle
2019-04-30
【python3学习笔记】斜杠和双斜杠运算符的区别
2019-04-30
【深度学习笔记】用torch.nn.Sequential()搭建神经网络模型
2019-04-30
【深度学习笔记】用torch.nn.ModuleList搭建神经网络
2019-04-30
【深度学习笔记】pytorch的点乘(dot product)
2019-04-30
【深度学习笔记】残差
2019-04-30
【python学习笔记】读取指定文件夹中的图片,结合边缘保留滤波EPF
2019-04-30
【工具和环境】Linux下安装pycharm
2019-04-30
【Accumulation】The definition of SISR
2019-04-30
【工具与环境】Windows下安装Sublime Text 3
2019-04-30
【工具与环境】Excel中批量插入行
2019-04-30