首页 > 代码库 > 栈—代码
栈—代码
#include <stdio.h>#include <malloc.h>#include <stdlib.h>//局部变量在栈里面分配。静态分配都在栈里面分配,动态都在堆里面分派的。typedef struct Node{ int data; struct Node *pNext;}NODE, * PNODE; //NODE等价于struct Node。PNODE等价于struct Node*typedef struct Stack{ PNODE pTop; PNODE pButtom;}STACK, * PSTACK;//void init(PSTACK);void push(PSTACK, int);void traverse(PSTACK);bool pop(PSTACK, int *);void clear(PSTACK);int main(void){ int val; STACK S; init(&S); push(&S, 1); push(&S, 2); push(&S, 3); push(&S, 4); push(&S, 5); push(&S, 6); push(&S, 7); push(&S, 8); traverse(&S); clear(&S); traverse(&S); if(pop(&S, &val)) { printf("出栈成功,出栈的元素是%d\n",val); } else { printf("出栈失败"); } return 0;}void init(PSTACK pS){ pS->pTop = (PNODE)malloc(sizeof(NODE)); if (NULL == pS->pTop) { printf("动态分配失败!\n"); exit(-1); } else { pS->pButtom = pS->pTop; pS->pButtom->pNext = NULL;//pS->pTop->pNext = NULL; }}void push(PSTACK pS, int val){ PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->data =http://www.mamicode.com/ val; pNew->pNext = pS->pTop; pS->pTop = pNew; return;}void traverse(PSTACK pS){ PNODE p = pS->pTop; while(p != pS->pButtom) { printf("%d", p->data); p = p->pNext; } printf("\n"); return;}bool empty(PSTACK pS){ if(pS->pButtom ==pS->pTop) return true; else return false;}//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中。如果出栈失败返回false。bool pop(PSTACK pS, int *pVal){ if(empty(pS)) //pS本身存放的就是S的地址 { return false; } else { PNODE q = pS->pTop; *pVal = q->data; pS->pTop = q->pNext; free(q); q = NULL; return true; }}//清空数据void clear(PSTACK pS){ if(empty(pS)) { return; } else { PNODE p = pS->pTop; PNODE q =NULL; while(p !=pS->pButtom) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pButtom; }}
栈—代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。