#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 100
typedef struct{
char * base;
char * top;
int stacksize;
}Sqstack;
void InitStack(Sqstack &S){
S.base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if(!S.base) exit(-1);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void GetTop(Sqstack S, char &e){
if(S.base == S.top)
exit(-1);
e = *(S.top-1);
}
bool Push(Sqstack &S, char e){
if(S.top - S.base >= S.stacksize){
S.base = (char*)realloc(S.base, (S.stacksize + STACKINCREMENT)*sizeof(char));
if(!S.base) return false;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
printf(" %c\n",e);
return true;
}
bool Pop(Sqstack &S, char &e){
if(S.base == S.top) return false;
e = *(--S.top);
return true;
}
int main(){
Sqstack S;
char ch;
InitStack(S);
for(int i = 0; i < 5; i++){
scanf("%c",&ch);
Push(S, ch);
}
GetTop(S, ch);
printf("%c\n",ch);
Pop(S,ch);
printf("%c\n",ch);
GetTop(S, ch);
printf("%c\n",ch);
system("PAUSE");
return 0;
}
C语言实现栈
最新推荐文章于 2023-08-24 16:06:59 发布