栈 (stack)
定义:
一种可以实现“先进后出”的数据存储。
分类:
静态栈:内部数组实现
动态栈:内部链表实现
链表实现:
# 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 pS) { pS ->pTop == (PNODE)malloc(sizeof(NODE)); //使pTop指向空链表的头节点 if(NULL == pS->pTop) { printf("分配内存失败"); exit(-1); } else { pS->pBottom = pS ->pTop //使pBottom指向空链表的头节点 pS ->pTop->pNext = null; //清空头节点的指针域 } } void traverse(PSTACK pS) { PNODE p = pS ->pTop; while(p!=pS->pBottom) { printf("%d" , p->data); p=p->pNext; } return; } bool empty(PSTACK pS) { if(pS->oTop ==pS ->pBottom) { return true; } else { return false; } } void pop (PSTACK pS ,int * pVal) { if(empty(pS)) { return false; } else { PNODE r = pS ->pTop; //把出栈元素 赋值临时节点 &pVal = r ->data; pS->pTop = r ->pNext; //把下个元素赋值给 TOP free(r); r= NULL; return true; } } //清空数据 void clear(PSTACK pS) { if(empty(pS)) { return false; } else { PNODE p = pS->pTop; PNODE q = NULL; //一下指向要释放的元素的指针域的值 while(p!=pS->pBottom) { q = p->pNext; free(p); p=q; } pS ->pTop = pS ->pBottom; } } //增加 void push(PSTACK pS, int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); //给val分配新的节点 pNew->data = val ; pNew -> pNext = pS->pTop; //新的节点指针域指向栈顶 pS->pTop = pNew; //pTop指向最新的节点 } int main (void) { int val; STACK S; //STACK 等价于struct Stack init(&S); //初始化 push(&S , 1);//压栈 pop (S ,&val); traverse(); //遍历输出 }
应用:
函数调用,表达式求职,内存分配,缓冲处理