#include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 100 //存储空间初始分配量 #define STACKINCREMENT 10 //存储空间分配增量 #define scanf scanf_s typedef int QElemType; typedef int Status; typedef struct QNode { QElemType* base; //在栈构造之前和销毁之后,base值为NULL QElemType* top; //栈顶指针 int stacksize; //当前已分配的存储空间,以元素为单位 }SqStack; //循环队列的初始化 void InitQueue(SqStack *S) { S->base = (QElemType*)malloc(STACK_INIT_SIZE * sizeof(int)); if (!S->base) exit(0); S->top = S->base; S->stacksize = STACK_INIT_SIZE; } //得到栈顶元素 ||也可以地址,自己修改 void GetTop(SqStack* S,QElemType* e) { if (S->top == S->base) exit(0); *e = *(S->top - 1); //不加括号错误 } //入栈 void Push(SqStack* S,int e) { if (S->top - S->base >= S->stacksize) //栈满,报错 exit(0); *S->top = e; printf("入栈地址:%p,元素:%d\n", S->top, *(S->top)); S->top++; //S->top = (S->top + 1); //这样也可以 } //出栈 void Pop(SqStack* S) { QElemType e; if (S->top == S->base) exit(0); S->top--; //不加括号也可以,但提示 e = *S->top; printf("出栈地址:%p,元素:%d\n", S->top, *(S->top)); } void output(SqStack* S) { SqStack* p = S; while (p->top != S->base) { p->top--; //不加括号也可以,但提示 printf("输出地址:%p,元素:%d\n",(p->top), * (p->top)); } } int main() { SqStack Q; int n , e; QElemType t; InitQueue(&Q); //初始化 printf("请输入入队的元素个数\n"); scanf_s("%d", &n); printf("请输入入队的元素\n"); while(n) { scanf_s("%d", &e); Push(&Q, e); n--; } GetTop(&Q, &t); printf("\n栈顶元素为:%d\n", t); printf("\n请输入出队的元素个数\n"); scanf_s("%d", &n); while (n) { Pop(&Q); n--; } printf("\n--------输出-------\n"); output(&Q); }