堆栈的链式存储 C语言实现

堆栈的链式存储 C语言实现,第1张

堆栈的链式存储 简单的PUSH和POP 写给自己平时复习和使用的,有需要的话可以写的更加详细一点
#include
#include
#include
typedef struct stack
{
    int data;
    struct stack *next;
}stack;

stack *InitStack(stack *top);  //初始化堆栈
void display(stack *top);  // 展示堆栈中的内容
stack *push(stack *top,int num);  
stack *pop(stack *top);

int main()
{
    stack *top=NULL;
    top=InitStack(top);
    top=push(top,10);
    display(top);
    printf("\n");
    top=push(top,20);
    display(top);
    printf("\n");
    pop(top);
    display(top);
    printf("\n");
    pop(top);
    display(top);
}


stack *InitStack(stack *top)
{
    top=(stack *)malloc(sizeof(stack));
    top->next=NULL;
    return top;
}
void display(stack *top)
{
    if(top->next==NULL)
     {
         printf("EMPTY");
         exit(0);
     }
    stack *p=top;
    while(p->next)  //top表示头节点,数据存储在top->next
    {
        p=p->next;
        printf("%d  \n",p->data);
    }
}
stack *push(stack *top,int num)
{
    stack *p;
    p=(stack *)malloc(sizeof(stack));
    p->data=num;
    p->next=top->next;
    top->next=p;
    return top;
}
 stack *pop(stack *top)
 {
     if(top->next==NULL)
     {
         printf("EMPTY");
         exit(0);
     }
     stack *p=top->next;
     top->next=top->next->next;
     free(p);
     return top;
 }

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

原文地址: https://outofmemory.cn/langs/713599.html

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

发表评论

登录后才能评论

评论列表(0条)

保存