行编辑程序(栈实现)

博客围绕行编辑程序展开,介绍其通过栈来实现的相关内容,栈作为一种重要的数据结构,在该程序中发挥关键作用,利用栈的特性可有效完成行编辑的各项操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<malloc.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef char SElemType;
typedef char Status;

struct SqStack
{
    SElemType *base;
    SElemType *top;
    int stacksize;
};
Status InitStack(SqStack &S)
{
    S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!S.base)exit(ERROR);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return OK;
}

Status Push(SqStack &S,SElemType e)
{
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!S.base) exit(ERROR);
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }
    *S.top++=e;
    return OK;
}

Status Pop(SqStack &S,SElemType &e)
{
    if(S.top==S.base)return ERROR;
    e=*--S.top;
    return OK;
}

Status GetTop(SqStack S)
{
    SElemType e;
    if(S.top==S.base)return ERROR;
    e=*(S.top-1);
    return e;
}

Status StackLength(SqStack S)
{
    return S.top-S.base;
}

Status StackTraverse(SqStack S)
{
    SElemType *p = (SElemType *)malloc(sizeof(SElemType));
    p =  S.top;
    if(p==S.base)printf("The Stack is Empty!");
    else
    {
        printf("The Stack is: ");
        p--;
        while(p!=S.base-1)
        {
            printf("%c", *p);
            p--;
        }
    }
    printf("\n");
    return OK;
}
Status DestoryStack(SqStack &S)
{
    free(S.base);
    S.base = NULL;
    S.top = NULL;
    S.stacksize = 0;
    return OK;
}
Status LinkClear(SqStack &S)
{
    S.top = S.base;
    return OK;
}
void LinkEdit(SqStack &S)
{
    char ch;
    SElemType e;
    ch = getchar();
    while(ch != EOF && ch != '\n')
    {
        switch(ch)
        {
        case '@':
            LinkClear(S);
            break;
        case '#':
            Pop(S,e);
            break;
        default:
            Push(S,ch);
        }
        ch = getchar();
    }
}
int main()
{
    SqStack S,T;
    SElemType e;
    InitStack(S);
    InitStack(T);
    while(1)
    {
        LinkEdit(S);
        while(StackLength(S))
        {
            Pop(S,e);
            Push(T,e);
        }
        StackTraverse(T);
        LinkClear(T);
    }
    DestoryStack(T);
    DestoryStack(S);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值