栈 ——C语言

栈 ——C语言,第1张

记录下的原因:

  • 可以督促自己,方便以后回看整。
  • 我希望能在你遇到的困难,需要求知的时候,可以给你提供一个有可能有解决问题的方法。
```javascript
// An highlighted block
#include 
#include 
#include 

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));
    if (NULL == ps->PTop) {
        printf("动态分布失败");
        exit(-1);
    }
    ps->pBottom = ps->PTop;
    ps->PTop->pNext = NULL;  //清空
}
  void push(PSTACK ps,int val){   
    PNODE pNew = (PNODE) malloc(sizeof(NODE));
    pNew->data = val;
    pNew->data = ps->PTop;
    ps->PTop = pNew;
}
void traverse(PSTACK PS){
    PNODE p = PS->PTop;
    while(p != PS->pBottom){
        printf("%d",p->data);
        p = p->pNext;
    }
}
_Bool empty(PSTACK PS){
    if(PS->PTop == PS->pBottom)
        return true;
    else
        return false;
}
 //把ps所指向的栈出栈一次,把出栈元素存入形参pval指向的变量
_Bool pool(PSTACK ps, int *pval){
    if(empty(ps)){   //ps本身存放的就是s地址
        return false;
    }
    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;
    }
}
int main() {
 STACK s;
 int val;
 init(&s);        //造出一个空栈
 push(&s,1);  //压栈
 push(&s,2);
 push(&s,3);
 push(&s,4);
 push(&s,5);
    traverse(&s);    //遍历
    clear(&s);
    traverse(&s); //遍历
 if( pool(&s,&val)){
     printf("出栈成功,出栈元素是%d\n",val);
 }
 else{
     printf("出栈失败\n");
 }
    return 0;
}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/676171.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-19
下一篇 2022-04-19

发表评论

登录后才能评论

评论列表(0条)

保存