# 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;// PSTACK 等价于 struct Stack * void init(PSTACK); //初始化 void push(PSTACK, int); //压栈 void traverse(PSTACK); //遍历输出 bool pop(PSTACK, int *); //出栈 void clear1(PSTACK); //清空 void clear2(PSTACK);//清空 int main(void) { STACK S; //STACK 等价于 struct Stack int val; init(&S); //初始化 目的是造出一个空栈 push(&S, 1); //压栈 push(&S, 2); push(&S, 3); push(&S, 4); push(&S, 5); push(&S, 6); traverse(&S); //遍历输出 if ( pop(&S, &val) ) //出栈 { printf("出栈成功!出栈的元素是:%d ", val); } else { printf("出栈失败! "); } traverse(&S); //遍历输出 clear2(&S); traverse(&S); //遍历输出 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; //pS->pBottom->pNext = NULL; } } void push(PSTACK pS, int val) //压栈 { PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->data = val; pNew->pNext = pS->pTop; //不能把 pS->Top 改为 pS->pBottom pS->pTop = pNew; return; } void traverse(PSTACK pS) //便利输出 { PNODE p = pS->pTop; while (p != pS->pBottom) { printf("%d ", p->data); p = p->pNext; } printf(" "); return; } bool empty(PSTACK pS) //判断是否空 { if (pS->pTop == pS->pBottom) { return true; } else { return false; } } //把PS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败返回false,否则返回true bool pop(PSTACK pS, int * pVal) { if ( empty(pS) ) // pS 形参本身保存的是 S 的地址,这里需要将S的地址发送给 empty() 函数只要发送 pS即可 { return false; } else { PNODE r = pS->pTop; //需要把他定义成已 pS->pTop 为类型的地址变量 *pVal = pS->pTop->data; //等价于 r->data pS->pTop = pS->pTop->pNext; //等价于 r->pNext free(r); //这里释放的是r所指向的动态内存 r = NULL; //这里表示清空地址变量 r 的数据以便下次分配 return true; } } void clear2(PSTACK pS) //清空 { PNODE p; int i; printf("清空的值都有:"); while ( pS->pTop != pS->pBottom ) { p = pS->pTop; i = p->data; printf("%d ", i); pS->pTop = p->pNext; free(p); p = NULL; } printf(" "); i = NULL; pS->pTop = pS->pBottom; } void clear1(PSTACK pS) //清空 { if ( empty(pS) ) { return; } else { PNODE p = pS->pTop; PNODE q = p->pNext; while (p != pS->pBottom) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pBottom; } }