使用堆栈的方式进行行编辑

这里只是模拟行编辑的核心代码,在下面的代码里,输入#可以后退一个字符,而输入@可以消除一行的字符

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define SIZE_OF_STACK 100 //确定栈的初始长度
#define SIZE_OF_NEW_STACK 10 //确定栈每次延展的长度
#define true 1 //个人习惯定义的类似布尔类型数据
#define false 0

typedef struct LineEdit
{
    char *base;
    char *top;
    int sizeOfStack;
}LINEEDIT;

int initStack(LINEEDIT *le);
int destroyStack(LINEEDIT *le);
int pushStack(LINEEDIT *le, char temp);
int popupStack(LINEEDIT *le);
int clearStack(LINEEDIT *le);
int visitStack(LINEEDIT le);

int main()
{

    char ch;
    LINEEDIT myLine;
    initStack(&myLine);

    while(ch != EOF)
    {
        printf("please input a string :\n");
        scanf("%c", &ch);
        while(ch != EOF && ch != '\n')
        {
            switch(ch)
            {
            case '#':
                popupStack(&myLine);
                break;
            case '@':
                clearStack(&myLine);
                break;
            default:
                pushStack(&myLine, ch);
            }
            scanf("%c", &ch);
        }
        visitStack(myLine);
        clearStack(&myLine);
        if(ch != EOF)
            scanf("%c", &ch);
    }
    destroyStack(&myLine);
    return 0;
}

int initStack(LINEEDIT *le)
{
    le->base = (char *)malloc(SIZE_OF_STACK * sizeof(char));
    if(le->base == NULL)
    {
        printf("fail to get memory!\n");
        exit(1);
    }
    le->top = le->base;
    le->sizeOfStack = SIZE_OF_STACK;
    return true;
}

int destroyStack(LINEEDIT *le)
{
    free(le->base);
    le->base = NULL;
    le->top = NULL;
    le->sizeOfStack = 0;
    return true;
}

int pushStack(LINEEDIT *le, char temp)
{
    if(le->top - le->base >= SIZE_OF_STACK)
    {
        le->base = (char *) realloc(le->base, SIZE_OF_NEW_STACK * sizeof(char));
        if(le->base == NULL)
        {
            printf("fail to get memory!\n");
            exit(1);
        }
        le->top = le->base + SIZE_OF_STACK;
        le->sizeOfStack += SIZE_OF_NEW_STACK;
    }
    *le->top++ = temp;
    return true;
}

int popupStack(LINEEDIT *le)
{
    if(le->top == le->base)
        return false;
    le->top--;
    return true;
}

int clearStack(LINEEDIT *le)
{
    le->top = le->base;
    return true;
}

int visitStack(LINEEDIT le)
{
    if(le.base == le.top)
        return false;
    while(le.base < le.top)
    {
        printf("%c", *(le.base++));
    }
    return true;
}
点赞