关闭

栈的应用—行编辑程序

64人阅读 评论(0) 收藏 举报
分类:

//Stack.h

#ifndef STACK_H

#define STACK_H

#define SElemType char
#define Status int

#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREAMENT 10 //存储空间分配增量

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1561次
    • 积分:130
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档