#include<stdio.h>
#include<stdlib.h>
#define STACK_SIZE 10
#define INCREASESIZE 1
typedef struct {
int stacksize;
int* base;
int* top;
}sqstack,*STACK;
void initstack(STACK S){
S->base=(int*)malloc(STACK_SIZE*sizeof(int));
S->top=S->base;
S->stacksize=STACK_SIZE;
}
void push(STACK S,int newdata){//压栈
if(S->top-S->base>STACK_SIZE){
S->base=(int*)realloc(S->base,(S->stacksize+INCREASESIZE)*sizeof(int));
S->top=S->base+S->stacksize;
++S->stacksize;
}
*S->top=newdata;
S->top++;
}
void pop(STACK S){//弹栈
if(S->top>S->base)
--S->top;
}
void printfstack(STACK S){
int* work=S->base;
while(S->top>work){
printf("%d ",*work);
work++;
}
}
main()
{
int num,i,newdata;
sqstack mystack;//其实所有的表在声明时都是结构体
initstack(&mystack);
printf("初始化成功!\n");
printf("请输入要创建的栈长度\n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("请输入第%d个数 ",i);
scanf("%d",&newdata);
push(&mystack,newdata);
}
printf("压栈成功!\n");
//printstack(&mystack);
printfstack(&mystack);
printf("\n打印成功!\n");
pop(&mystack);
printf("\n弹栈成功!\n");
printfstack(&mystack);
printf("\n打印成功!\n");
system("pause");
return 0;
}
#include<stdlib.h>
#define STACK_SIZE 10
#define INCREASESIZE 1
typedef struct {
int stacksize;
int* base;
int* top;
}sqstack,*STACK;
void initstack(STACK S){
S->base=(int*)malloc(STACK_SIZE*sizeof(int));
S->top=S->base;
S->stacksize=STACK_SIZE;
}
void push(STACK S,int newdata){//压栈
if(S->top-S->base>STACK_SIZE){
S->base=(int*)realloc(S->base,(S->stacksize+INCREASESIZE)*sizeof(int));
S->top=S->base+S->stacksize;
++S->stacksize;
}
*S->top=newdata;
S->top++;
}
void pop(STACK S){//弹栈
if(S->top>S->base)
--S->top;
}
void printfstack(STACK S){
int* work=S->base;
while(S->top>work){
printf("%d ",*work);
work++;
}
}
main()
{
int num,i,newdata;
sqstack mystack;//其实所有的表在声明时都是结构体
initstack(&mystack);
printf("初始化成功!\n");
printf("请输入要创建的栈长度\n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("请输入第%d个数 ",i);
scanf("%d",&newdata);
push(&mystack,newdata);
}
printf("压栈成功!\n");
//printstack(&mystack);
printfstack(&mystack);
printf("\n打印成功!\n");
pop(&mystack);
printf("\n弹栈成功!\n");
printfstack(&mystack);
printf("\n打印成功!\n");
system("pause");
return 0;
}