您的位置:首页 > 其它

试利用栈的基本操作编写一个行编辑程序,当前一个字符有误时,输入#消除,当前面一行有误时,输入@消除前面行的字符序列

2015-02-09 16:57 696 查看
头文件:函数的声明

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

#define STACKSIZE 100

typedef char ElemType;
typedef struct
{
ElemType stack[STACKSIZE];
int top;
}SeqStack;

void InitStack(SeqStack *S);//初始化栈
int StackEmpty(SeqStack S);//判断栈是否为空
int GetTop(SeqStack S,ElemType *e);//取栈顶元素
int PushStack(SeqStack *S,ElemType e);//入栈
int PopStack(SeqStack *S,ElemType *e);//出栈
int StackLength(SeqStack S);//求栈长度
void ClearStack(SeqStack *S);//清空栈
void LineEdit();//行编辑函数


函数的定义
#include "行编辑函数.h"

void InitStack(SeqStack *S)//将栈S初始化为空栈
{
S->top = 0;
}
int StackEmpty(SeqStack S)//判断栈是否为空,栈为空返回1,否则返回0
{
if(0 == S.top)
{
return 1;
}
else
{
return 0;
}
}
int GetTop(SeqStack S,ElemType *e)//取栈顶元素,将栈顶元素值返回给e,并返回1表示成功,返回0表示失败
{
if(S.top <= 0)
{
printf("栈已经空!\n");
return 0;
}
else
{
*e = S.stack[S.top-1];//取栈顶元素
return 1;
}
}
int PushStack(SeqStack *S,ElemType e)//进栈操作
//将元素e进栈,元素进栈成功返回1,否则返回0
{
if(S->top >= STACKSIZE-1)
{
printf("栈已满,不能入栈!");
return 0;
}
else
{
S->stack[S->top] = e;
S->top++;
return 1;
}
}
int PopStack(SeqStack *S,ElemType *e)//出栈操作
{
if(S->top <= 0)
{
printf("栈已经没有元素,不能出栈!\n");
return 0;
}
else
{
S->top--;
*e = S->stack[S->top];
return 1;
}
}
int StackLength(SeqStack S)//返回栈长度
{
return S.top;
}
void ClearStack(SeqStack *S)//清空栈
{
S->top = 0;
}

void LineEdit()//行编辑函数
{
SeqStack S;
char ch;
ElemType e;
ElemType a[50];
int i,j = 0;
InitStack(&S);
printf("输入字符序列(#表示前一个字符无效,@表示当前行字符无效).\n");
ch = getchar();
while(ch != '\n')
{
switch(ch)
{
case '#':
if(!StackEmpty(S))
{
PopStack(&S,&ch);//栈顶元素出栈
}
break;
case '@':
ClearStack(&S);//清空栈
break;
default:
PushStack(&S,ch);//字符进栈
}
ch = getchar();//读入下一个字符
}
while(!StackEmpty(S))
{
PopStack(&S,&e);//字符出栈并存入数组中
a[j++] = e;
}
for(i = j-1;i >= 0;i--)
{
printf("%c",a[i]);//输出正确的字符序列
}
printf("\n");
ClearStack(&S);//为下一次输入做准备
}


函数的应用

#include "行编辑函数.h"

int main(void)
{
LineEdit();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐