#include "stdio.h"
#include "stdlib.h"
typedef int E;
struct Stack{
E * array;
int capacity;
int top;
};
typedef struct Stack * ArrayStack;
int initStack(ArrayStack stack){
stack->array = (E*)malloc(sizeof(E) * 10);
if(stack->array == NULL) return 0;
stack->capacity = 10;
stack->top = -1;
return 1;
}
int pushStack(ArrayStack stack,E element){
if(stack->top+1==stack->capacity){
int newCapacity = stack->capacity+(stack->capacity >> 1);
E * newArray = (E*)realloc(stack->array,newCapacity*sizeof(E));
if(newArray == NULL) return 0;
stack->array = newArray;
stack->capacity = newCapacity;
}
stack->array[stack->top+1] = element;
stack->top++;
return 1;
}
void printStack(ArrayStack stack){
printf("| ");
for (int i = 0; i < stack->top + 1; ++i) {
printf("%d, ", stack->array[i]);
}
printf("\n");
}
int isEmpty(ArrayStack stack){
return stack->top == -1;
}
int popStack(ArrayStack stack){
return stack->array[stack->top--];
}
int main(){
struct Stack stack;
initStack(&stack);
for (int i = 0; i < 3; ++i) {
pushStack(&stack, i*100);
}
printStack(&stack);
while (!isEmpty(&stack)) {
printf("%d ", popStack(&stack)); //将栈中所有元素依次出栈
}
}
最后修改:2025 年 07 月 09 日
© 允许规范转载