【数据结构】栈应用 行编辑器

来源:互联网 发布:淘宝网1元秒杀专区 编辑:程序博客网 时间:2024/06/06 10:42

在终端输入一串字符 当发现刚刚输入的字符有误,可以输入 # ,表示前一个字符无效;当想清除该行 则输入 @ 


例如:

  `   输入: hellow#

               输出:              hello


     输入:hellow@

                输出:              



#ifndef _EDIT_H_#define_EDIT_H_#include <iostream>  #include <stdlib.h>  #include <malloc.h>  using namespace std;#define STACKSIZE 100  typedef 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();//行编辑函数  #endif

#include"Edit.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){cout << "栈已经空!"<<endl;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){cout<<"栈已满,不能入栈!";return 0;}else{S->stack[S->top] = e;S->top++;return 1;}}int PopStack(SeqStack *S, ElemType *e)//出栈操作  {if (S->top <= 0){cout<<"栈已经没有元素,不能出栈!"<<endl;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);cout<<"输入字符序列(#表示前一个字符无效,@表示当前行字符无效)"<<endl;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--){cout<<a[i];//输出正确的字符序列  }cout << endl;ClearStack(&S);//为下一次输入做准备  }

#include"Edit.h"int main(void){LineEdit();return 0;}


3 0
原创粉丝点击