栈的应用-行编辑(线性存储)

#include<iostream.>
using namespace std;
const int OK = 1;
const int overflow = -2;
const int TRUE = 1;
const int FALSE = 0;
const int ERROR = -1;
const int MAX_STACK_SIZE = 100;
const int MAXLERENTSIZE = 10;
typedef struct
{
	//注意,不论是线性表(栈),在用线性存储表示时
	//一般不要规定某个数组,即赋予初始值
	//因情况的不同,数组的范围也无法确定,所以用指针再堆进行动态分配表示
	char *top;//栈顶指针
	char *base;//栈底指针
	int stacksize;
	int length;
}SqStack;
/******函数声明******/
int InitStack(SqStack& S);
int Push(SqStack& S, char e);
int Pop(SqStack& S, char& e);
int ClearStack(SqStack& S);
int LineEdit(SqStack& S);
int DestoryStack(SqStack& S);
int Show(SqStack S);
/*****main****/
int main()
{
	SqStack S1;
	InitStack(S1);
	cout << "Please input your text;" << endl;
	LineEdit(S1);
	DestoryStack(S1);
	return OK;
}
/**********函数定义**********/
int InitStack(SqStack& S)
{
	S.base = (char*)malloc(MAX_STACK_SIZE * sizeof(char));
	if (!S.base)
	{
		exit(overflow);
	}
	S.top = S.base;
	S.length = 0;
	S.stacksize = MAX_STACK_SIZE;
	return OK;
}
int Push(SqStack& S, char e)
{
	if (S.top - S.base >= MAX_STACK_SIZE)
	{
		S.base = (char*)realloc(S.base, (MAXLERENTSIZE + MAX_STACK_SIZE) *
			sizeof(char));
		if (!S.base)
		{
			exit(overflow);
		}
		S.top = S.base + MAX_STACK_SIZE;
		S.stacksize = MAXLERENTSIZE + MAX_STACK_SIZE;
	}
	*S.top++ = e;
	S.length++;
	return OK;
}
int Pop(SqStack& S, char& e)
{
	if (S.base == S.top)
	{
		return ERROR;
	}
	e = *--S.top; //先自减,再取值
	return OK;
}
int ClearStack(SqStack& S)
{
	S.top = S.base;
	return OK;
}
int LineEdit(SqStack& S)
{
	char e1;  //作为Push和Pop函数的第二个实参
	char ch = getchar(); //ch相当于光标
	while (ch != '.') //假定'.'为文本结束符
	{
		while (ch != '.' && ch != '\n')
		{
			switch (ch)
			{
			case '#':
				Pop(S, e1);
				break;
			case '@':
				ClearStack(S);
				break;
			default:
				Push(S, ch);
				break;
			}
			ch = getchar();
		}
		if (ch != '.')
		{
			ch = getchar();
		}
		Show(S); //字符串已经先存在缓冲区,而getchar()函数从缓冲区中逐一读取
	}
	
	ClearStack(S);
	return OK;
}
int DestoryStack(SqStack& S)
{
	free(S.base);
	S.base = NULL; //避免成为"野指针"
	S.top = NULL;
	S.length = 0;
	S.stacksize = 0;
	return OK;
}
int Show(SqStack S)
{
	cout << "TRUE:";
	while (S.base != S.top)
	{
		cout << *(S.base);
		S.base++;
	}
	cout << endl;
	return OK;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值