文本行编辑

本文介绍了一个使用栈数据结构实现的简易文本编辑器。该编辑器支持基本的文本输入、撤销(#)及清除(@)功能,并通过动态调整大小的顺序栈来管理文本变化。文章详细展示了栈的初始化、判断是否为空、元素的压入与弹出等关键操作。

#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -1
//#define EOF -1
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 1000
#define MAXQSIZE 10

static int i=0;
typedef char ElemType;
typedef struct StackNode//构造栈
{
 ElemType *base;
    ElemType *top;
    int stacksize;
}SqStack;

ElemType InitStack(SqStack *S)//初始化栈
{
 S->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
    if(!S->base)
 {
  exit(OVERFLOW);
 }
 S->top=S->base;
    S->stacksize=STACK_INIT_SIZE;
    return OK;
}

ElemType StackEmpty(SqStack *S)//判断栈是否为空
{
 if(S->top==S->base)
  return OK;
    else
  return ERROR;
}

ElemType Push(SqStack *S,ElemType e)//进栈操作
{
 if(S->top-S->base>=S->stacksize)
 {
  S->base = (ElemType *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(ElemType));
        if(!S->base)
  {
   exit(OVERFLOW);
        }
  S->top = S->base+S->stacksize;
        S->stacksize+=STACKINCREMENT;
 }
    *S->top++=e;
    return OK;
}

ElemType Pop(SqStack *S,ElemType *e)//出栈操作
{
 

 if(S->top==S->base)
 {
  return ERROR;
 }
    *e=*--S->top;
     //printf("%d/n",e);
   // return e;
   return 0;
}

void ClearStack(SqStack *S)//清空栈
{
 S->top=S->base;
}

ElemType LineEdit(SqStack *S )//文本编译
{
 char ch, e, a[30];
    int i ;
 ch = getchar();
  
 
 while(1) 
 { 
  while (ch!='/n')
  {
       switch(ch)
   {
       case '#':
     Pop(S,&e);
                    break;
                case '@':
        ClearStack(S);
     break;
    default:
     Push(S,ch);
     break;
   }
    ch = getchar();
  }
        i = 0;
     while (!StackEmpty(S))
  {
              Pop(S,&e);
        a[i++]=e;
  }
     for(--i; i>= 0; i--)
  {
   printf("%c",a[i]);
  }
        printf("/n");
  ClearStack(S);
     ch = getchar();
 }
  
  return 0;
}

int main(void)
{
 
 SqStack S;
   
 InitStack(&S);
 LineEdit(&S);

 system("pause");
 return 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值