试利用栈的基本操作编写一个行编辑程序,当前一个字符有误时,输入#消除,当前面一行有误时,输入@消除前面行的字符序列

来源:互联网 发布:淘宝天天特价是假货吗 编辑:程序博客网 时间:2024/05/01 10:08

头文件:函数的声明

#include <stdio.h>#include <stdlib.h>#include <malloc.h>#define STACKSIZE 100typedef char ElemType;typedef struct{ElemType stack[STACKSIZE];int top;}SeqStack;void InitStack(SeqStack *S);//初始化栈int StackEmpty(SeqStack S);//判断栈是否为空int GetTop(SeqStack S,ElemType *e);//取栈顶元素int PushStack(SeqStack *S,ElemType e);//入栈int PopStack(SeqStack *S,ElemType *e);//出栈int StackLength(SeqStack S);//求栈长度void ClearStack(SeqStack *S);//清空栈void LineEdit();//行编辑函数


函数的定义

#include "行编辑函数.h"void InitStack(SeqStack *S)//将栈S初始化为空栈{S->top = 0;}int StackEmpty(SeqStack S)//判断栈是否为空,栈为空返回1,否则返回0{if(0 == S.top){return 1;}else{return 0;}}int GetTop(SeqStack S,ElemType *e)//取栈顶元素,将栈顶元素值返回给e,并返回1表示成功,返回0表示失败{if(S.top <= 0){printf("栈已经空!\n");return 0;}else{*e = S.stack[S.top-1];//取栈顶元素return 1;}}int PushStack(SeqStack *S,ElemType e)//进栈操作//将元素e进栈,元素进栈成功返回1,否则返回0{if(S->top >= STACKSIZE-1){printf("栈已满,不能入栈!");return 0;}else{S->stack[S->top] = e;S->top++;return 1;}}int PopStack(SeqStack *S,ElemType *e)//出栈操作{if(S->top <= 0){printf("栈已经没有元素,不能出栈!\n");return 0;}else{S->top--;*e = S->stack[S->top];return 1;}}int StackLength(SeqStack S)//返回栈长度{return S.top;}void ClearStack(SeqStack *S)//清空栈{S->top = 0;}void LineEdit()//行编辑函数{SeqStack S;char ch;ElemType e;ElemType a[50];int i,j = 0;InitStack(&S);printf("输入字符序列(#表示前一个字符无效,@表示当前行字符无效).\n");ch = getchar();while(ch != '\n'){switch(ch){case '#':if(!StackEmpty(S)){PopStack(&S,&ch);//栈顶元素出栈}break;case '@':ClearStack(&S);//清空栈break;default:PushStack(&S,ch);//字符进栈}ch = getchar();//读入下一个字符}while(!StackEmpty(S)){PopStack(&S,&e);//字符出栈并存入数组中a[j++] = e;}for(i = j-1;i >= 0;i--){printf("%c",a[i]);//输出正确的字符序列}printf("\n");ClearStack(&S);//为下一次输入做准备}


函数的应用

#include "行编辑函数.h"int main(void){LineEdit();return 0;}


0 0
原创粉丝点击