【資料結構】棧應用 行編輯器,資料結構編輯器
在終端輸入一串字元 當發現剛剛輸入的字元有誤,可以輸入 # ,表示前一個字元無效;當想清除該行 則輸入 @
例如:
` 輸入: 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;}