栈的应用:简单行编辑器(C语言实现)

设立一个缓冲区,用以接受用户输入的一行字符,然后逐行存入用户数据区,允许用户输入出差错,并在发现有误的时候可以加以改正。

“#”是退格符,表示前一个字符无效;“@”是退行符,表示当前行中的字符均无效。

"main.c"
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"

/*
'#'为退格符,'@'为退行符
*/

void LineEditor();
void printStack(Stack* s);
void clearStack(Stack* s);

int main() {
    LineEditor();
    return 0;
}

void LineEditor() {
    printf("Welcome to Line Editor\n");
    printf("'#' to delete a letter, '@' to delete the whole line!\n");
    printf("Let's begin:\n");
    Stack s;
    InitStack(&s);
    char ch = getchar();
    if((ch == '#' || ch == '@') && isEmpty(&s)) { printf("nothing to delete!"); exit(1); }
    push(&s, ch);
    while(ch != EOF) {
        while(ch != EOF && ch != '\n') {
            switch (ch)
            {
            case '#':
                pop(&s);
                break;
            case '@':
                clearStack(&s);
                break;
            default:
                push(&s, ch);
                break;
            }
            ch = getchar();
        }
        printStack(&s);
        printf("\n");
        if(ch != EOF) { 
            ch = getchar(); 
            if((ch == '#' || ch == '@') && isEmpty(&s)) { printf("nothing to delete!"); exit(1); }
        }
    }
}


void printStack(Stack* s) {
    //利用递归实现栈内元素逆序打印
    if(isEmpty(s)) { return; }
    else {
        ElementType i = pop(s);
        printStack(s);
        printf("%c", i);
    }
}

void clearStack(Stack* s) {
    while(!isEmpty(s)) { pop(s); }
}
"stack.h"
#ifndef STACK_H
#define STACK_H

#define ElementType char
//结构体的声明以及定义
typedef struct node {
    ElementType data;
    struct node* next;
} Node;

typedef struct stack {
    Node* top;
    int size;
} Stack;

//各种函数的声明
void InitStack(Stack* s);
void push(Stack* s, ElementType data);
ElementType pop(Stack* s);
ElementType peek(Stack* s);
_Bool isEmpty(Stack* s);

#endif


"stack.c"
#include <stdlib.h>
#include <stdbool.h>
#include "stack.h"

void push(Stack* s, ElementType data) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = s->top;
    s->top = node;
    s->size++;
}

ElementType pop(Stack* s) {
    if (isEmpty(s)) {
        return -1; // 栈为空,返回 -1 表示出错
    }
    Node* node = s->top;
    ElementType data = node->data;
    s->top = node->next;
    s->size--;
    free(node);
    return data;
}

ElementType peek(Stack* s) {
    if (isEmpty(s)) {
        return -1; // 栈为空,返回 -1 表示出错
    }
    return s->top->data;
}

_Bool isEmpty(Stack* s) {
    return s->size == 0;
}

void InitStack(Stack* s) {
    s->size = 0;
    s->top = NULL;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值