首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言基礎

簡單行編輯器實現:棧數據結構處理退格與行刪除命令

     編輯:C 語言基礎

程序功能

實現一個基於行的簡單編輯器,支持:

  • 普通字符輸入
  • #:退格刪除前一字符(棧彈出)
  • @:刪除整行(清空棧)
  • 換行提交:將當前行字符逆序輸出(雙棧翻轉)

核心數據結構:順序棧

#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

struct SqStack {
    char *base;
    char *top;
    int stacksize;
};

void InitStack(SqStack &S) {
    S.base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
    if (!S.base) exit(1);
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack &S, char e) {
    if (S.top - S.base >= S.stacksize) {
        S.base = (char*)realloc(S.base, (S.stacksize+STACKINCREMENT)*sizeof(char));
        if (!S.base) exit(1);
        S.top = S.base + S.stacksize;
        S.stacksize += STACKINCREMENT;
    }
    *S.top++ = e;
}
char Pop(SqStack &S, char &e) {
    if (S.top == S.base) return 0;
    e = *--S.top;
    return e;
}
void ClearStack(SqStack &S) { S.top = S.base; }
bool StackEmpty(SqStack &S) { return S.top == S.base; }
void DestroyStack(SqStack &S) { free(S.base); S.top = S.base; }

主編輯循環

void main() {
    char ch, e;
    SqStack S, D;  // S: 當前行棧, D: 輸出翻轉棧
    InitStack(S); InitStack(D);
    ch = getchar();
    while (ch != EOF) {
        while (ch != EOF && ch != '\n') {
            switch (ch) {
                case '#': Pop(S, e); break;      // 退格
                case '@': ClearStack(S); break;  // 刪除整行
                default: Push(S, ch); break;     // 普通字符入棧
            }
            ch = getchar();
        }
        // 行結束,將 S 逆序轉入 D 再輸出
        while (!StackEmpty(S)) { Pop(S, e); Push(D, e); }
        while (!StackEmpty(D)) { Pop(D, e); printf("%c", e); }
        ClearStack(S);
        if (ch != EOF) ch = getchar();
    }
    DestroyStack(S);
}

算法亮點

  • 雙棧翻轉實現行內字符順序輸出(棧本身後進先出)。
  • 動態擴容棧避免溢出。
  • 即時字符處理(getchar()),無需緩衝整行。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved