《資料結構》嚴蔚敏 用棧實現行編輯程式
阿新 • • 發佈:2019-01-12
參考文章:https://blog.csdn.net/Vit_rose/article/details/52781086
核心程式碼:void LineEdit(SqStack L)
//order stack //接受使用者輸入在緩衝區中,使用者發現輸入錯誤的時候,可以補一個退格符"#",“@”退行符 //input: whli# #ilr#e(s# *s) // [email protected](* s= # ++); //output: while(*s) // putchar(*s++) #include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 typedef char SElemType; typedef int Status; typedef struct { SElemType *base; SElemType *top; int stackesize; }SqStack; Status InitStack(SqStack *S) { (*S).base =(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SqStack)); if(!S->base) exit(ERROR); (*S).top = (*S).base; // If you don't understand it ,I think you should learn about the structure in C firstly. (*S).stackesize = STACK_INIT_SIZE; return OK; } // Well,Remeber,It's only use in allocation stack dynamic Status ClearStack(SqStack *S) { //(*S).top = (*S).base; while(S->base != S->top) S->top -- ; S->stackesize = 0; return OK; } Status StackEmpty(SqStack *S) { if(S->top == S->base) return TRUE; else return FALSE; // or use ? : make things seems concise } // When Push,first add then change the point Status Push(SqStack *S,SElemType e) { //lack of verfy if(S->top - S->base >= S->stackesize) { S->base = (SElemType*)realloc(S->base, (S->stackesize + STACK_INIT_SIZE)*sizeof(SElemType)); if(!S->base) exit(ERROR); S->top = S->base + S->stackesize; S->stackesize += STACKINCREMENT; } ////////// the first //// *(*S).top = e; S->top ++; return OK; } Status Pop(SqStack *S) { if(StackEmpty(S) == 0) { S->top --; return OK; } else return ERROR; } Status DestoryStack(SqStack *S) { if(S->stackesize > 0) { S->stackesize = 0; } free(S); S = NULL; return OK; } void LineEdit(SqStack L) { char c,ch,*p; printf("輸入:"); ch = getchar(); //從終端接收第一個字元 while(ch != EOF){ printf("輸出:"); while(ch != EOF && ch != '\n'){ switch(ch) { case '#': Pop(&L); break; case '@': ClearStack(&L); break; default : Push(&L,ch); break; }//switch ch = getchar(); //從終端接收下一個字元 }//while p = L.base; // 我就死在這一步上 是char *型別 while(p != L.top){ printf("%c",*p); ++p; } printf("\n"); ClearStack(&L); if(ch != EOF) printf("輸入:"); ch = getchar(); } } int main(int argc, char const *argv[]) { SqStack L; InitStack(&L); LineEdit(L); return 0; }