睡觉前总算完成了!!
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
# define STACK_INIT_SIZE 20
# define STACKINCREMENT 10
typedef struct Stack
{
char * base;
char * top;
int stacksize;
}* PSTACK, STACK;
void InitStack (PSTACK pS)
{
pS->base = (char *)malloc(sizeof(char) * STACK_INIT_SIZE);
if (!pS->base)
{
printf("内存分配失败!\n");
exit(-1);
}
pS->top = pS->base;
pS->stacksize = STACK_INIT_SIZE;
return;
}
void Push (PSTACK pS, char ch)
{
if (pS->top - pS->base == pS->stacksize - 1)
{
pS->base = (char *)realloc(pS->base, pS->stacksize + STACKINCREMENT);
if (!pS->base)
{
printf("内存分配失败!\n");
exit(-1);
}
pS->stacksize += STACKINCREMENT;
}
*pS->top++ = ch;
return;
}
void Pop (PSTACK pS)
{
if (pS->top != pS->base)
{
--pS->top;
--pS->stacksize;
}
return;
}
void Clear (PSTACK pS)
{
pS->top = pS->base;
return;
}
void Traverse (PSTACK pS)
{
PSTACK p = pS;
while (p->top != p->base)
{
printf("%c", *pS->base++);
}
return;
}
int main(void)
{
char ch;
STACK s;
InitStack(&s);
printf("开始输入:");
do
{
ch = getchar();
if (ch == '#')
{
Pop(&s);
}
else if (ch == '@')
{
Clear(&s);
}
else
{
Push(&s, ch);
}
} while ('\n' != ch);
printf("------------------------\n输入结果:");
Traverse(&s);
return 0;
}