栈清空程序演示
#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;}}
?
總結
- 上一篇: php ci 表单校验,表单验证 -
- 下一篇: oracle 日志的容量,oracle