当前位置 : 主页 > 网络编程 > 其它编程 >

栈的操作(创建,入栈,出栈,清空,遍历等等)

来源:互联网 收集:自由互联 发布时间:2023-07-02
#include#include#includetypedefstructNode{intdata;structNode*pNext;}NODE,*PNODE #include#include#includetypedef struct Node{int data;struct Node *pNext;}NODE,*PNODE;typedef struct Stack{PNODE pTop;PNODE pBottom;}STACK,*PSTACK;void init(PSTAC
#include#include#includetypedefstructNode{intdata;structNode*pNext;}NODE,*PNODE #include#include#includetypedef struct Node{int data;struct Node *pNext;}NODE,*PNODE;typedef struct Stack{PNODE pTop;PNODE pBottom;}STACK,*PSTACK;void init(PSTACK pS);void push (PSTACK pS,int val);void traverse(PSTACK pS);bool pop(PSTACK pS,int * pVal);bool empty(PSTACK pS);void clear(PSTACK pS);int main(){    STACK S;int val;init(//造出一个空栈for(int i=0;i<=15;i++){      push(}/*push(//压栈push(push(push( push(push(*/    traverse(//遍历输出//出栈//pop(if(pop(}else{     printf("出栈成功");}     traverse(//遍历输出//traverse(//遍历输出    clear(//清空    if(empty(}else{          printf("栈为非空\n");}return 0;}void init(PSTACK pS){pS->pTop=(PNODE)malloc(sizeof(NODE));if(NULL==pS->pTop){printf("动态内存分配失败");exit(-1);}else{pS->pBottom = pS->pTop;pS->pTop->pNext = NULL;}}void push (PSTACK pS,int val){PNODE pNew=(PNODE)malloc(sizeof(NODE));pNew->data=val;pNew->pNext=pS->pTop;pS->pTop=pNew;return;}void traverse(PSTACK pS){PNODE p=pS->pTop;while(p!=pS->pBottom){printf("%d  ",p->data);p=p->pNext;}printf("\n");}bool empty(PSTACK pS){if(pS->pTop==pS->pBottom){return true;}else{return false;}}bool pop(PSTACK pS,int * pVal){if(empty(pS))//pS存放的就是栈的地址{return true;}else{        PNODE r = pS->pTop;* pVal = r->data;pS->pTop = r->pNext;free(r);r = NULL;return true;}}void clear(PSTACK pS){if(empty(pS)){return;}else{PNODE p=pS->pTop;PNODE q=NULL;while(p!=pS->pBottom){q=p->pNext;free(p);p=q;}pS->pTop=pS->pBottom;}}

版权声明:本文为博主原创文章,未经博主允许不得转载。

栈的操作(创建,入栈,出栈,清空,遍历等等)

【文章原创作者:东台网站设计公司 http://www.1234xp.com/dongtai.html 欢迎留下您的宝贵建议】
上一篇:ASP如何使用MYSQL数据库
下一篇:没有了
网友评论