#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>typedef struct Node{int data;struct Node * pNext;
}NODE,*PNODE;typedef struct Stack{PNODE pTop; //栈顶元素PNODE pBottom; //栈底部元素
}STACK,*PSTACK;void init(PSTACK);
void push(PSTACK, int);
void traverse(PSTACK);bool pop(PSTACK, int *p);
bool empty(PSTACK ps); //判空void clear(PSTACK ps); //清空int main(void){STACK s; //等价于struct Stackinit(&s); //初始化push(&s,1); //压栈 push(&s, 2);push(&s, 3);push(&s, 4);push(&s, 5);push(&s, 6);push(&s, 7);traverse(&s); //遍历输出//清空栈clear(&s);traverse(&s); //遍历输出int val; //保存出栈的元素//出栈一个元素if (pop(&s, &val)) {printf("出栈成功,出栈的元素是%d\n", val);}else {printf("出栈失败,出栈的元素是%d\n", val);}traverse(&s); //遍历输出while (true){ }return 0;
}//初始化造出一个空栈
void init(PSTACK ps) {ps->pTop = (PNODE)malloc(sizeof(NODE));if (NULL == ps->pTop) {printf("动态内存失败");exit(-1);}else {ps->pBottom= ps->pTop;ps->pTop->pNext = NULL;}
}//压栈
void push(PSTACK ps, int val) {//构造一个新的节点PNODE pNew=(PNODE)malloc(sizeof(NODE));pNew->data = val;pNew->pNext = ps->pTop;ps->pTop = pNew;
}//遍历
void traverse(PSTACK ps) {PNODE p = ps->pTop;while (p != ps->pBottom) {printf("%d ",p->data);p = p->pNext;}printf("\n");return;
}//把ps所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败,返回false,否则返回true
bool pop(PSTACK ps, int *pVal) {//如果为空返回falseif (empty(ps)) {return false;}else {PNODE tmp = ps->pTop; //构造一个临时节点,存放ps指向顶部元素的地址(顶部元素是要出栈的)*pVal = tmp->data; //出栈的元素ps->pTop=tmp->pNext;free(tmp);tmp = NULL;return true;}}bool empty(PSTACK ps) {if (ps->pTop == ps->pBottom) {return true;}else {return false;}
}void clear(PSTACK ps) {if (empty(ps)) {return;}else {//构造一个临时节点指针p存放栈顶节点的地址PNODE p = ps->pTop;PNODE q = NULL; //构造一个临时节点指针q 将q指针的地址置空while (p != ps->pBottom) { //p != ps->pBottom 表示这不是一个空栈 然后就循环q = p->pNext; //将栈顶元素下一个元素的地址给qfree(p); //把栈顶元素p释放p = q; //把q又赋值给p此时 p就指向了栈顶的下一个元素,由于栈顶元素被释放,此时p又是栈顶元素}ps->pTop = ps->pBottom;}}