栈的C语言实现

来源:互联网 发布:源码授权是什么 编辑:程序博客网 时间:2024/05/01 10:21

这里写图片描述

#include<stdio.h>#include<stdbool.h>#include<malloc.h>typedef struct Node{       int val;       struct Node *pNext;}NODE,*PNODE;typedef struct stack{       PNODE pTop;       PNODE pBottom;}STACK,*PSTACK;void init(PSTACK pStack){       PNODE p=(PNODE)malloc(sizeof(NODE));       if(p==NULL){              printf("Dynamic storage fail to distribute!");              exit(-1);       }else{       pStack->pBottom=p;       pStack->pTop=p;       }       return pStack;}bool push(PSTACK pStack,int val){       PNODE pNew =(PNODE)malloc(sizeof(NODE));         if(pStack==NULL){              printf("Dynamic storage fail to distribute!");              exit(-1);       }       pNew->val=val;       pNew->pNext=pStack->pTop;       pStack->pTop=pNew;       return true;}void showStack(PSTACK pStack){       if(pStack==NULL){              printf("stack is null");              exit(-1);       }       PNODE temp=pStack->pTop;       while(temp!=pStack->pBottom){            printf("%d ",temp->val);            temp=temp->pNext;       }}bool pop(PSTACK p){       if(p->pTop==p->pBottom){              printf("stack is null\n");              return false;       }       PNODE temp=p->pTop;       p->pTop=p->pTop->pNext;       free(temp);       temp=NULL;       return true;}int main(void){       STACK s;       init(&s);       push(&s,3);       push(&s,5);       push(&s,3);       push(&s,67);       pop(&s);       pop(&s);       pop(&s);       pop(&s);       pop(&s);       push(&s,67);       push(&s,67);       push(&s,67);       showStack(&s);}
0 0
原创粉丝点击