#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;
}
栈的应用-行编辑(线性存储)
最新推荐文章于 2024-03-03 18:52:30 发布