#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define stackIncrement 10
typedef struct{
int* base;
int* top;
int stacksize;
}sqStack;
bool init_stack(sqStack* stack)
{
stack->base = (int*)malloc(sizeof(int));
if(!stack->base)return false;
stack->top = stack->base;
stack->stacksize = STACK_INIT_SIZE;
return true;
}
bool get_top(sqStack* stack,int* e)
{
if(stack->base == stack->top)return false;
*e = *(stack->top-1);
return true;
}
bool stack_push(sqStack* stack,int e)
{
if(stack->top - stack->base >= stack->stacksize)
{
stack->base = (int*)realloc(stack->base,(stack->stacksize + stackIncrement)*sizeof(int));
if(!stack->base)return false;
stack->top = stack->base + stack->stacksize;
stack->stacksize += stackIncrement;
}
*stack->top = e;
printf("top = %p, top.data= %d\n",stack->top,*stack->top);
stack->top += 1;
return true;
}
bool pop(sqStack* stack,int* e)
{
if(stack->top == stack->base)return false;
stack->top -= 1;
*e = *stack->top;
return true;
}
int main()
{
sqStack stack1;
init_stack(&stack1);
int a[] = {1,2,3,4,5,6,7,8,9,0};
bool ok = true;
int i = 0;
printf("----------push----------\n");
for(int i = 0;i<sizeof(a)/sizeof(a[0]);i++)
{
stack_push(&stack1,a[i]);
}
printf("---------push over----------\n");
printf("----------pop----------\n");
for(int j = 0;j<10 && ok;j++)
{
ok = pop(&stack1,&i);
printf("top = %p, top.data = %d\n",stack1.top,i);
}
printf("---------pop over----------\n");
return 1;
}
栈的实现
最新推荐文章于 2025-04-24 20:09:49 发布