如何让栈的空间可以无限扩容(realloc)
我想一直输入字符 比如说几百个几千个?假设内存是足够的#define STACK_INIT_SIZE 30
#define STACKINCREMENT 20
void Push(sqStack *s, ElemType e)
{
if ((s->top) - (s->base) >= (s->StackSize))
{
s->base = (ElemType*)realloc(s->base, (s->StackSize + STACKINCREMENT) * sizeof(ElemType));
if (s->base == NULL)
{
exit(0);
}
}
*(s->top) = e;
s->top = s->top + 1;
s->StackSize = s->StackSize + STACKINCREMENT;
}
while (c != '\n')
{
Push(&s, c);
scanf("%c", &c);
} 可以用链栈#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;//栈内数据的类型
typedef struct ListStackNode{ //定义栈节点
ElemType date;
struct ListStackNode *next;
}StackNode,*ListStack;
//初始化栈
ListStack InitListStack(ListStack S){
S=(ListStack)malloc(sizeof(StackNode));
S->next=NULL;
return S;
}
//进栈操作
int ListStackPush(ListStack S,ElemType e){
StackNode *s=NULL;
s=(StackNode*)malloc(sizeof(StackNode));
s->date=e;
s->next=S->next;
S->next=s;
return 0;
}
int main()
{
ListStack S=NULL;
S=InitListStack(S);//初始化栈
ElemType x;
scanf("%c",&x);
while(x!='\n'){ //输入字符,以回车键结束
ListStackPush(S,x);//入栈
scanf("%c",&x);
}
return 0;
}
页:
[1]