首页 > 代码库 > 关于动态栈的分析
关于动态栈的分析
栈属于数据结构,它本质上属于线性表,只是受限的线性表。
我们今天来讨论下动态栈也就是链栈的相关问题。
# include <stdio.h> # include <stdlib.h> # include <malloc.h> typedef struct Node { int data; struct Node* pNext; }NODE, *PNODE; typedef struct Stack { PNODE pTop; //栈顶 PNODE pBottom; //栈底 }STACK, *PSTACK; //初始化空栈 void InitStack(PSTACK pS) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if(NULL == pS->pTop) { printf("ERROR \n"); exit(-1); } else { pS->pBottom = pS->pTop; pS->pBottom->pNext = NULL; //pS->pTop->pNext = NULL; } } //遍历栈 void TraverseStack(PSTACK pS) { printf("Now start traverse the stack elem : "); PNODE p = pS->pTop; while(p != pS->pBottom) { printf("%d ", p->data); p = p->pNext; } printf("\n"); } //压栈 void PushStack(PSTACK pS, int Val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->data = Val; pNew->pNext = pS->pTop; pS->pTop = pNew; } //判断栈空 bool IsEmptyStack(PSTACK pS) { if(pS->pTop == pS->pBottom) { return true; } else { return false; } } //出栈 int PopStack(PSTACK pS, int * pVal) { if(IsEmptyStack(pS)) { printf("ERROR stack is empty \n"); exit(-1); } else { PNODE r = pS->pTop; *pVal = r->data; pS->pTop = r->pNext; free(r); r = NULL; } return true; } //清空栈 void ClearStack(PSTACK pS) { printf("Now start clear the stack ... "); if(IsEmptyStack(pS)) { return ; } PNODE p = pS->pTop; PNODE q = NULL; while(p != pS->pBottom) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pBottom; puts("\n"); } //主程序 int main(void) { STACK S; InitStack(&S);//造成一个空栈 //压栈 PushStack(&S, 1); PushStack(&S, 2); PushStack(&S, 3); PushStack(&S, 4); //遍历 TraverseStack(&S); //弹出栈顶元素 int val = 0; if(PopStack(&S, &val)) { printf("pop stack top elem is %d \n\n", val); } //遍历 TraverseStack(&S); //清空栈 ClearStack(&S); //遍历 TraverseStack(&S); return 0; }
本文出自 “享受科技带来的快乐” 博客,请务必保留此出处http://liam2199.blog.51cto.com/2879872/1532114
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。