标签:tom size tac data empty span next main void
一种可以实现 " 先进后出 " 的存储结构。
栈类似于箱子
静态栈:以数组的形式生成的栈。
动态栈:以链表的形式生成的栈。
出栈
压栈
# 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; } STATCK,*PSTACK; //初始化一个栈 void init(PSTACK pS); //遍历一个栈 void traverse(PSTACK pS); //压栈 void push(PSTACK pS,int val); //出栈 bool pop(PSTACK pS,int *val); //clear void clear(PSTACK pS); int main(void) { STATCK S; int val; init(&S); push(&S,3); push(&S,4); push(&S,7); push(&S,9); traverse(&S); if(pop(&S,&val)) { printf("出栈的值是%d!\n",val); } else { printf("出栈失败!\n"); } traverse(&S); clear(&S);//清空栈 traverse(&S);//清空成功 return 0; } //初始化栈 //初始化的目的就是将pTop和pBottom两个指针指向同一个没有实际意义的头结点这样就实现了栈的初始化 void init(PSTACK pS) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if(NULL == pS->pTop) { printf("动态内存分配失败!\n"); exit(-1); } else { pS->pBottom = pS->pTop; pS->pTop->pNext = NULL; } } //遍历一个栈 void traverse(PSTACK pS) { PNODE p = pS->pTop; while(p!=pS->pBottom) { printf("%d ",p->data); p = p->pNext; } printf("\n"); return; } //压栈 void push(PSTACK pS,int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); if(NULL == pNew->pNext) { printf("动态内存分配失败!\n"); exit(-1); } pNew->pNext = NULL; pNew->data = val; pNew->pNext = pS->pTop; pS->pTop = pNew; return; } bool empty(PSTACK pS) { if(pS->pTop == pS->pBottom) { return true; } else { return false; } } bool pop(PSTACK pS,int *val) { if(empty(pS)) { printf("栈为空\n"); return false; } else { PNODE p = pS->pTop; *val = p->data; pS->pTop = p->pNext; free(p); p = NULL; return true; } } void clear(PSTACK pS) { if(empty(pS)) { return; } else { PNODE p; p = pS->pTop; PNODE q = NULL; while (p!=pS->pBottom) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pBottom; } }
标签:tom size tac data empty span next main void
原文地址:http://www.cnblogs.com/strator/p/7233334.html