栈结构实现 发表于 2018-03-06 | 分类于 c++ | 123456789101112131415161718192021222324252627282930#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>#include<stdbool.h>typedef struct Stack //定义栈模型{ PNODE TOP; PNODE BUTTOM;}*PSTACK,STACK;/*栈定义的模型初始化方法,压入栈的方法,出栈的方法,遍历的方法,*///初始化栈的操作void init_stack(PSTACK);//压入栈void push_stack(PSTACK, int);//出栈void pop_stack(PSTACK, int*);//遍历void traverse(PSTACK);//是否为空bool empty(PSTACK);//clear;void clear(PSTACK); 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980/*实现上述栈的函数*///初始化void init_stack(PSTACK phead){ PNODE stack = (PNODE)malloc(sizeof(NODE)); if (stack == NULL){ printf("创建失败!"); return ; } phead->BUTTOM = stack; phead->TOP = phead->BUTTOM; phead->TOP->next = NULL;}//入栈void push_stack(PSTACK phead, int val){ PNODE pnew = (PNODE)malloc(sizeof(NODE)); pnew->data = val; pnew->next = phead->TOP; phead->TOP = pnew;}//出栈void pop_stack(PSTACK phead, int *val){ if (empty(phead)) { return; } PNODE p = phead->TOP; *val = p->data; phead->TOP = p->next; free(p); p = NULL;}//遍历void traverse(PSTACK phead){ PNODE p = phead->TOP; while (phead->BUTTOM!=p) { printf("%d", p->data); p = p->next; }}//是否为空bool empty(PSTACK phead){ if (phead->BUTTOM == phead->TOP) return true; return false;}//clearvoid clear(PSTACK phead){ if (empty(phead)) return; PNODE p = phead->TOP; while (p != phead->BUTTOM) { phead->TOP = p->next; free(p); p = phead->TOP; }}void main(){ STACK stack; int val; init_stack(&stack); //初始化 if (empty(&stack)) // printf("空stack\n"); push_stack(&stack, 1);//push push_stack(&stack, 2); push_stack(&stack, 3); traverse(&stack); //遍历 pop_stack(&stack, &val); clear(&stack); //clear pop_stack(&stack, &val); printf("%d", val); pop_stack(&stack, &val); pop_stack(&stack,&val); //pop system("pause");} 版权声明:本文为博主原创,如若转载请标明出处https://dword.top/栈结构.html -------------end-------------