#ifndef _SQ_STACK_ #define _SQ_STACK_ typedef struct { int *base; int *top; int stack_size; }SqStack; #endif // ! _SQ_STACK_
#ifndef _STACKOP_ #define _STACKOP_ void Init_Stack(SqStack *s); void Destory_Stack(SqStack *s); void Get_Top(SqStack *s, int *e); void Push(SqStack *s, int e); void Pop(SqStack *s, int *e); void Print_Stack(SqStack s); #endif // !_STACKOP_
#include <stdio.h> #include <stdlib.h> #include "SqStack.h" #include "StackOp.h" #define MAX 100 //initial size #define INCREMENT 10 //incremental size //top=base作为栈空的标志;top指针始终指向栈顶元素的下一个位置 void Init_Stack(SqStack *s) { s->base = (int *)malloc(MAX * sizeof(int)); //指针数组操作 s->top = s->base; s->stack_size = MAX; } void Destory_Stack(SqStack *s) { free(s->base); } //非空栈时,返回top-1的栈顶元素的值 void Get_Top(SqStack *s, int *e) { if (s->top == s->base) { printf("Wrong!\n"); } else { *e = *(s->top - 1); } } void Push(SqStack *s, int e) { //入栈 if (s->top - s->base >= s->stack_size) { //栈满,加空间 s->base = (int *)realloc(s->base, (MAX + INCREMENT) * sizeof(int)); //指针数组操作 s->top = s->base + s->stack_size; s->stack_size += INCREMENT; } *(s->top)++ = e; } void Pop(SqStack *s, int *e) { //出栈 if (s->top == s->base) { //空栈 printf("Wrong!\n"); } else { *e = *--(s->top); } } void Print_Stack(SqStack s) { printf("The stack is:\n"); s.top -= 1; //top指针指向栈顶元素 for (; s.top >= s.base; s.top--) { printf("%d\n", *s.top); } }
#include <stdio.h> #include <stdlib.h> #include "SqStack.h" #include "StackOp.h" int main() { SqStack stack; Init_Stack(&stack); int num = 0; do { printf("input numbers to stack\n"); scanf("%d", &num); if (num != -1) { Push(&stack, num); } } while (num != -1); Print_Stack(stack); int e = 0; Pop(&stack, &e); Print_Stack(stack); return 0; }