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

来源:互联网 发布:app刷量软件源码 编辑:程序博客网 时间:2024/04/28 02:28

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

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

"SequenceStack.h":

#ifndef _SEQUENCESTACK_H#define _SEQUENCESTACK_H//定义顺序栈结构体typedef struct {SElemType *base;  //指向栈低,base=NULL表示栈销毁或不存在SElemType *top;   //指向栈顶int stack_size;       //栈的容量大小}SqStack;//初始化栈Status init_sq_stack(SqStack &S);//进栈Status push(SqStack &S, SElemType e);//出栈Status pop(SqStack &S,SElemType &e);//打印栈Status display_sq_stack(SqStack S);#endif

"SequenceStack.c":

#include"init.h"#include"SequenceStack.h"#define SqStackSize 100#define SqStackIncrement 30//初始化栈Status init_sq_stack(SqStack &S){S.base = (SElemType *)malloc(SqStackSize * sizeof(SElemType));//内存分配失败if(!S.base)exit(OVERFLOW);S.top = S.base;S.stack_size = SqStackSize;return OK;}//进栈Status push(SqStack &S, SElemType e){if(S.top - S.base >= S.stack_size){S.base = (SElemType *)realloc(S.base,(S.stack_size + SqStackIncrement)*sizeof(SElemType));//内存分配失败if(!S.base)exit(OVERFLOW);S.top = S.base + S.stack_size;S.stack_size += SqStackIncrement;}*S.top++ = e;return OK;}//出栈Status pop(SqStack &S,SElemType &e){if(S.top -S.base == 0){printf("栈为空,不能出栈\n");return ERROR;}e = *--S.top;return OK;}//打印栈Status display_sq_stack(SqStack S){if(NULL == S.base){printf("栈不存在\n");return ERROR;}SElemType *p;p = S.top;do{printf("%c     ", *--p);}while(p != S.base);printf("\n");return OK;}

"main.c":

#include"init.h"#include"SequenceStack.h"void test_sequence_stack(){SqStack S;init_sq_stack(S);push(S,'a');push(S,'b');push(S,'c');printf("栈中的元素为:");display_sq_stack(S);SElemType e;pop(S,e);printf("出栈的元素为:%c\n",e);}int main(){test_sequence_stack();}

运行结果如下:


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