#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>// 每一个节点的数据类型
typedef struct Node
{int data;struct Node * pNext;
}NODE, * PNODE; // NODE等价 struct Node PNODE等价于 struct Node *// 栈
typedef struct Stack
{PNODE pTop;PNODE pBottom;
}STACK, * PSTACK;void init(PSTACK pS);
void push(PSTACK pS, int val);
void traverse(PSTACK pS);
bool pop(PSTACK pS, int * val);
bool empty(PSTACK pS);
void clear(PSTACK pS);// 这是一个动态栈
int main(void) {STACK s; // STACK 等价于 stack Stackinit(&s);// 目的是造出一个空栈push(&s, 1);push(&s, 2);push(&s, 3);push(&s, 4);traverse(&s);int val;if (pop(&s, &val)){printf("出栈成功 出栈的元素是%d\n", val);} else {printf("出栈失败\n");}traverse(&s);clear(&s);traverse(&s);if (pop(&s, &val)){printf("出栈成功 出栈的元素是%d\n", val);} else {printf("出栈失败\n");}return 0;
}void init(PSTACK pS) {pS->pTop = (PNODE)malloc(sizeof(NODE));if (NULL == pS->pTop){printf("动态内存分配失败");exit(-1);}pS->pTop->pNext = NULL; // 初始化头结点为NULLpS->pBottom = pS->pTop;
}void push(PSTACK pS, int val) {PNODE pNew = (PNODE)malloc(sizeof(NODE));pNew->data = val; // 填充新数据pNew->pNext = pS->pTop; // 追加结果pS->pTop = pNew;// 更新top
}void traverse(PSTACK pS) {PNODE p = pS->pTop;printf("开始打印\n");while (p != pS->pBottom){printf("%d ", p->data);p = p->pNext;}printf("结束打印\n");
}bool empty(PSTACK pS) {if (pS->pTop == pS->pBottom){return true;}return false;}bool pop(PSTACK pS, int * val) {if (empty(pS)){return false;}*val = pS->pTop->data;PNODE r = pS->pTop;pS->pTop = pS->pTop->pNext;free(r);r = NULL;return true;
}void clear(PSTACK pS) {if (empty(pS)){return;}PNODE p = pS->pTop;PNODE q = NULL;while (p != pS->pBottom){q = p->pNext;free(p);p = q;}pS->pTop = pS->pBottom;
}
运行效果