要求:整体输入,调整内容后整体输出(其中#退格,@代表退行)。
#include#include #define OK 1 #define ERROR 0 #define MAX_SIZE 5 #define INIT_SIZE 2 typedef char ElemType; typedef int status; typedef struct Lnode { ElemType *top;//栈顶指针 ElemType *base;//栈底指针 int max;//最大存储量 int size;//实际存储量 }Lnode;//节点类型 //1.栈的初始化 status Init_Stack(Lnode *p) { p->base=(ElemType*)malloc(INIT_SIZE*sizeof(ElemType));//初始化数组 if(!p->base) { printf("栈初始化失败n"); exit(0);//初始化失败退出 } p->max=INIT_SIZE;//一些初始数据的赋值 p->size=0; p->top=p->base;//头尾指针统一 return OK; } //2.入栈 status Push_Stack(Lnode *p,ElemType e) { if(p->top-p->base>=p->max)//判断是否需要扩容 { p->base=(ElemType*)realloc(p->base,(MAX_SIZE+p->max)*sizeof(ElemType)); if(!p->base)//扩容失败退出 return ERROR; p->top=p->base+p->max;//头指针调位置(防止产生存储空间不足,在其他存储空间开辟新的) p->max=MAX_SIZE+p->max;//max修改 } p->size++; *p->top=e; p->top++; return OK; } //3.输出 ElemType Print_Stack(Lnode *p) { ElemType e; if(p->size==0) { e=0;//栈为空 return e; } p->size--; e=*p->base; p->base++; return e; } int main() { Lnode p; int i,j; ElemType e; //1.栈的初始化 Init_Stack(&p); //2.入栈 printf("请输入数据(输入!结束输入)n"); while(1) { scanf("%c",&e); if(e=='!') break; Push_Stack(&p,e); if(e=='@')//@表示退格 栈顶下一位 { p.top--; p.size--; } if(e=='#')//#表示退行 栈顶归零(等于栈底) { p.top=p.base; p.size=0; } } printf("n"); //3.输出 while(p.size!=0) { e=Print_Stack(&p); printf("%c",e); } } ———————————————— 版权声明:本文为CSDN博主「小灰灰呀!」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_57399201/article/details/120947967



