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

头文件:函数的声明

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值