//编译环境 visual studio 2008,win32 console application.
//SqStack.c
//顺序栈
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACKINITSIZE 100//初始化空间分配量
#define STACKINCREASEMENT 10//分配增量
typedef char elemType;//元素类型
typedef struct
{
elemType *top;
elemType *base;
int stacksize;
}SqStack;
//初始化栈
int InitStack(SqStack *s)
{
s->base=(elemType *)malloc(STACKINITSIZE*sizeof(elemType));
if(!s->base) exit(OVERFLOW);
s->top=s->base;
s->stacksize=STACKINITSIZE;
return OK;
}
//获取栈的长度(元素个数)
int StackLength(SqStack *s)
{
int length=0;
elemType *p=s->base;
while(p!=s->top)//自下朝上增加
{
p++;
length++;
}
return length;
}
//获取栈的长度(元素个数),另一种方法
void GetLength(SqStack *s)
{
printf("栈的元素个数为%d\n",s->top-s->base);
}
//遍历栈,自顶向下
int StackTraverse(SqStack *s)
{
elemType *p=s->top;
printf("该栈自顶向下的元素为:\n");
while(p!=s->base)
{
p--;
printf("%c",*p);
}
printf("\n");
return OK;
}
//获取栈顶元素
int GetTop(SqStack *s)
{
if(s->top==s->base)
printf("栈为空\n");
return ERROR;
printf("%c",*(s->top-1));
return OK;
}
//插入值为e的栈顶元素
int Push(SqStack *s,elemType e)
{
if(s->top-s->base==s->stacksize)//栈满,插入栈顶元素需要重新分配空间
{
s->base=(elemType *)realloc(s->base,(s->stacksize+STACKINCREASEMENT)*sizeof(elemType));
if(!s->base) exit(OVERFLOW);
s->top=s->base+STACKINCREASEMENT;
}
//*(s->top++)=e;
*(s->top)=e;
s->top++;//top指向栈顶元素的上方,先赋值,再top++
return OK;
}
//删除栈顶元素
int Pop(SqStack *s)
{
if(s->base==s->top)
{
printf("栈为空\n");
return ERROR;
}
//printf("已删除栈顶元素 %c\n",*(--s->top));
s->top--;
printf("已删除栈顶元素 %c\n",*(s->top));//top指向栈顶元素的上方,先top--,再输出值
return OK;
}
//判断栈是否为空
void StackEmpty(SqStack *s)
{
if(s->top==s->base)
printf("该栈为空\n");
else
printf("该栈不为空\n");
}
//清空栈
int ClearStack(SqStack *s)
{
if(s->base==s->top)
printf("栈已经为空\n");
else
{s->base=s->top;
printf("栈已经被清空\n");
}
return OK;
}
main()
{
SqStack *s=(SqStack*)malloc(sizeof(SqStack));
InitStack(s);
StackEmpty(s);
printf("插入栈顶元素...\n");
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
StackEmpty(s);
StackTraverse(s);
printf("栈的元素个数为%d\n",StackLength(s));
//GetLength(s);
Pop(s);
StackTraverse(s);
//printf("栈的元素个数为%d\n",StackLength(s));
GetLength(s);
ClearStack(s);
StackEmpty(s);
printf("栈的元素个数为%d\n",StackLength(s));
//GetLength(s);
}
数据结构的C实现_顺序栈
最新推荐文章于 2022-07-23 10:15:52 发布