#include"stdlib.h"
#include"stdio.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int elem;
typedef void Status;
typedef struct MyStruct
{
elem *top;
elem *base;
int stacksize;
}stack;
Status Initstack(stack &S){
S.base=(elem*)malloc(STACK_INIT_SIZE * sizeof(elem));
if (!S.base) exit(0);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
}
Status GetTop(stack S,elem &e){
if (S.top==S.base)
{
exit(0);
}
e=*(S.top-1);
}
Status Push(stack &S,elem e){
if (S.top-S.base==S.stacksize-1)
{
S.base=(elem*)realloc(S.base,(STACKINCREMENT+S.stacksize) * sizeof(elem));
}
if(!S.base) exit(0);
S.stacksize+=STACKINCREMENT;
*S.top++=e;
}
Status Pop(stack &S,elem &e){
if(S.base==S.top) exit(0);
e=*--S.top;
}
int StackEmpty(stack S){
if(S.base==S.top) return 1;
else return 0;
}
void ClearStack(stack &S){
elem e;
while (!StackEmpty(S))
{
Pop(S,e);
}
}
void DestroyStack(stack &S){
for (int i = 0; i < S.stacksize; i++)
{
free(S.base++);
}
}
//栈的应用
//十进制转八进制
void conversion(int N){
stack S;
elem e;
Initstack(S);
while (N)
{
Push(S,N%8);
N=N/8;
}
while (!StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
putchar('\n');
}
//利用栈实现行编辑
void LineEdit(){
stack S;
elem e;
Initstack(S);
char ch=getchar();
while (ch!=EOF)
{
while (ch!=EOF&&ch!='\n')
{
switch (ch)
{
case '#':Pop(S,e);break;
case '@':ClearStack(S);break;
default:Push(S,ch);break;
}
ch=getchar();
}
/**
这一步用于传输数据,不写
*/
ClearStack(S);
if(ch!=EOF) ch=getchar();
}
DestroyStack(S);
}
void main(){
LineEdit();
}
c语言之栈
最新推荐文章于 2025-03-30 18:05:30 发布