<数据结构>链栈的C语言实现

来源:互联网 发布:北京网络推广 编辑:程序博客网 时间:2024/04/19 14:09

       栈的概念,想必来看这篇文章的,都应该是清楚的。栈是线性表的一个子集,限定了对于表的一些操作,仅能在表尾进行插入和删除操作。话不多说,直接给出自己写的源代码(仅供参考):

PS:程序简单实现,重在理解知识点,打牢基础。

"init.h":

#ifndef _INIT_H#define _INIT_H#include<stdio.h>#include<stdlib.h>#define TRUE 1#define FASLE 0#define OK 1#define ERROR -1#define OVERFLOW -2typedef int Status;typedef char SElemType;#endif

"LinkStack.h":

#ifndef _LINKSTACK_H#define _LINKSTACK_Htypedef struct SNode{SElemType data;struct SNode * next;}SNode, *LinkNode;typedef struct{LinkNode top;int size;}LinkStack;//初始化链栈Status init_link_stack(LinkStack &LS);//进栈Status push(LinkStack &LS,SElemType e);//出栈Status pop(LinkStack &LS,SElemType &e);//获得栈顶元素SElemType get_top(LinkStack LS);//打印栈Status display_link_stack(LinkStack LS);#endif

"LinkStack.c":

#include"init.h"#include"LinkStack.h"//初始化链栈Status init_link_stack(LinkStack &LS){LS.top = (LinkNode)malloc(sizeof(SNode));LS.top->next = NULL;LS.size = 0;return OK;}//进栈Status push(LinkStack &LS,SElemType e){LinkNode p = (LinkNode)malloc(sizeof(SNode));p->next = LS.top->next;LS.top->next = p;p->data = e;++LS.size;return OK;}//出栈Status pop(LinkStack &LS,SElemType &e){if(LS.size == 0){printf("栈为空,不能出栈\n");return ERROR;}e = LS.top->next->data;LinkNode p = LS.top->next;LS.top->next = LS.top->next->next;--LS.size;free(p);return OK;}//获得栈顶元素SElemType get_top(LinkStack LS){if(LS.size == 0){printf("栈为空,无元素\n");}return LS.top->next->data;}//打印栈Status display_link_stack(LinkStack LS){LinkNode p;p = LS.top->next;while(p){printf("%c     ",p->data);p = p->next;}printf("\n");return OK;}

“main.c”:

#include"init.h"#include"LinkStack.h"void test_link_stack(){LinkStack S;init_link_stack(S);push(S,'a');push(S,'b');push(S,'c');printf("栈中的元素为:");display_link_stack(S);SElemType e;pop(S,e);printf("出栈的元素为:%c\n",e);}int main(){test_link_stack();        return 0;}


结果如下:



与大家分享,共同学习,相互提高,如有疑问或建议,请留言。

原创粉丝点击