栈的概念,想必来看这篇文章的,都应该是清楚的。栈是线性表的一个子集,限定了对于表的一些操作,仅能在表尾进行插入和删除操作。话不多说,直接给出自己写的源代码(仅供参考):
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 -2
typedef 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();
}
运行结果如下:
与大家分享,共同学习,相互提高,如有疑问或建议,请留言。