#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#define CharStackCapacitySize 100
typedef struct Element
{
char data;//字符内容
}Ele;//栈元素类型的结构体
typedef struct Char_Stack
{
Ele *top;//栈顶后邻指针
Ele *base;//栈底前邻指针,不存数据
int ElementNumberLimit;//目前字符容量
}cstack;//栈类型的结构体
cstack Create_CharStack()//建一个空栈
{
cstack ex_stack;
ex_stack.base = (Ele*)malloc(CharStackCapacitySize*sizeof(Ele));
ex_stack.top = ex_stack.base+1;//刚开始没有数据
ex_stack.ElementNumberLimit = (int)CharStackCapacitySize;//元素容量根据宏常量被赋值
return ex_stack;
}
cstack Pop_CharStack(cstack ex_stack)//删除栈顶的元素
{
if(ex_stack.top==ex_stack.base+1)//判断是否空栈是否还可删除
{
printf("Zero Element in This Stack\n");
return ex_stack;
}
ex_stack.top--;//栈顶位置前移
return ex_stack;
}
cstack Push_CharStack(cstack ex_stack,char NewData)//在栈顶加新元素
{
if(ex_stack.top-ex_stack.base>=ex_stack.ElementNumberLimit)//判断元素容量满了没有是否需要申请更大内存
{
ex_stack.base = (Ele*)realloc(ex_stack.base,(ex_stack.ElementNumberLimit+CharStackCapacitySize)*sizeof(Ele));
if(!ex_stack.base)//申请失败的跳出
{
printf("Alloc Memory Fail\n");
exit(0);
}
ex_stack.top = ex_stack.base+ex_stack.ElementNumberLimit;//重置栈顶后邻元素指针位置
ex_stack.ElementNumberLimit+=CharStackCapacitySize;//更新栈的容量属性值
}
(ex_stack.top++)->data = NewData;//新元素的添加
return ex_stack;
}
int print_CharStack(cstack ex_stack)//显示栈里的字符序列内容
{
Ele *ptr;
if(ex_stack.top==ex_stack.base+1)//通过判断栈顶后邻元素指针是否和栈底前邻元素指针相邻判断是否栈空
{
printf("Zero Element in This Stack\n");
return 0;
}
for(ptr=ex_stack.base+1;ptr<ex_stack.top;ptr++)//注意开始条件和结束条件,只输出有数据的元素
{
printf("%c",ptr->data);
}
printf("\n");
}
char Get_TopData(cstack ex_stack)//获取栈顶数据
{
return (--ex_stack.top)->data;
}
int Get_StackCapacity(cstack ex_stack)//获取栈容量
{
return ex_stack.ElementNumberLimit;
}
int Get_StackEleNum(cstack ex_stack)//获取栈元素数量
{
return (int)(ex_stack.top-1-ex_stack.base);
}
cstack Clear_Stack(cstack ex_stack)//清栈
{
ex_stack.top = ex_stack.base+1;
return ex_stack;
}
int main()
{
cstack ex;
ex = Create_CharStack();//栈的诞生
print_CharStack(ex);//此时是空栈屏幕会提示没数据
ex=Push_CharStack(ex,'O');
ex=Push_CharStack(ex,'K');
ex=Push_CharStack(ex,'8');
ex=Push_CharStack(ex,'3');//先压栈4次,栈内存着OK83
print_CharStack(ex);//显示压进去的4个字符
printf("%d\n",Get_StackEleNum(ex));//显示字符数
ex=Pop_CharStack(ex);
ex=Pop_CharStack(ex);//出栈两次,栈内存着OK
print_CharStack(ex);//显示余下的两个字符
printf("%c\n",Get_TopData(ex));//获取栈顶数据
ex=Pop_CharStack(ex);
ex=Pop_CharStack(ex);//栈空
ex=Pop_CharStack(ex);//提示栈空不能出栈
print_CharStack(ex);//显示空栈提示
printf("%d\n",Get_StackCapacity(ex));//显示当前字符容量
int i;
ex=Push_CharStack(ex,'E');
ex=Push_CharStack(ex,'x');
ex=Push_CharStack(ex,'p');
ex=Push_CharStack(ex,'e');
ex=Push_CharStack(ex,'n');
ex=Push_CharStack(ex,'d');
for(i=0;i<50;i++)
{
ex=Push_CharStack(ex,'F');
ex=Push_CharStack(ex,'A');
}//由于达到元素数量限制,又重新申请了CharStackCapacitySize大小的新空间给ex栈
print_CharStack(ex);//正常显示106个字符
printf("%c\n",Get_TopData(ex));
printf("%d\n",Get_StackCapacity(ex));//这时的元素容量为200
ex=Clear_Stack(ex);//清栈
print_CharStack(ex);
return 0;
}
C语言对栈的操作
最新推荐文章于 2024-09-18 23:38:52 发布