栈的应用—行编辑程序

来源:互联网 发布:赵照声律启蒙知乎 编辑:程序博客网 时间:2024/05/20 22:40

//Stack.h

#ifndef STACK_H

#define STACK_H

#define SElemType char
#define Statusint

#define STACK_INIT_SIZE100 //存储空间初始分配量
#define STACKINCREAMENT10 //存储空间分配增量

typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

Status InitStack(SqStack *S); //初始化栈
Status Push(SqStack *S, SElemType e); //压栈
Status Pop(SqStack *S, SElemType *e); //出栈
Status ClearStack(SqStack *S);

#endif

//Stack.c

#include "Stack.h"
#include <stdlib.h>

 Status InitStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)
return 1;
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return 0;
 }


 Status Push(SqStack *S, SElemType e)
 {
if(S->stacksize == S->top - S->base){//栈满
S->top = (SElemType *)realloc(S->base,
(S->stacksize + STACKINCREAMENT) * sizeof(SElemType));
if(!S->base)
return 1;
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREAMENT;
}
*S->top++ = e;
return 0;
 }

 Status Pop(SqStack *S, SElemType *e)
 {
if(0 == S->top - S->base)//栈空
return 1;
*e = *--S->top;
return 0;
 }

 Status ClearStack(SqStack *S)
 {
S->top = S->base;
return 0;
 }


//main.c

#include <stdio.h>
#include "Stack.h"


SqStack S ;
char ch = 0; //从终端接收一个字符

void LineEdit();

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

void LineEdit()
{
ch = getchar();
InitStack(&S);//初始化一个空栈
while( ch != EOF)
{
while(ch != EOF && ch != '\n'){//每次读一行数据
switch(ch){
case '#':
Pop(&S,&ch);
break;
case '@':
ClearStack(&S);
break;
default:
Push(&S, ch);
}
ch = getchar();//从终端接收下一个字符
}
while(S.top - S.base != 0)//测试代码
printf("%c", (Pop(&S, &ch), ch));

ClearStack(&S);//读取下一行,并将栈置空
ch = getchar();
}
}

0 0