栈的链式实现(c语言)

这篇博客介绍了如何使用C语言实现链式栈,包括初始化、入栈、出栈、获取栈顶元素和计算栈内元素个数等操作。通过示例代码展示了栈的使用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
/*实现链栈*/
typedef struct StackNode{
    int data;
    struct StackNode *next;
}StackNode;
/*初始化*/
StackNode * initStack(){
    StackNode * stack;
    stack -> next = (StackNode *)malloc(sizeof(StackNode));
    stack -> next = NULL;
    return stack;
}
/*入栈*/
int push(StackNode * stack,int elem){
    StackNode * elemNode = (StackNode *)malloc(sizeof(StackNode));
    elemNode -> data = elem;
    elemNode -> next = stack -> next;
    stack -> next = elemNode;
    return 1;
}
/*出栈*/
int pop(StackNode * stack){
    int topElem;
    if(stack -> next == NULL) return 0;
    StackNode * p = stack -> next;
    topElem = stack -> next -> data;
    stack -> next = stack -> next -> next;
    free(p);
    return topElem;
}
/*取栈顶元素*/
int getTop(StackNode * stack){
    if(!stack -> next) return 0;
    return stack -> next -> data;
}
/*显示栈的元素个数,由自己实现!*/
int getStackLen(StackNode * stack){
    int stackLen = 0;
    while(stack -> next){
        stackLen ++;
        stack = stack -> next;
    }
    return stackLen;
}
int main()
{
    int topElem = -1;

    StackNode * stack = initStack();
    push(stack, 100);
    push(stack, 200);
    push(stack, 300);
    push(stack, 400);
    printf("本次出栈的元素为:%d\n",pop(stack));

    topElem = getTop(stack);
    printf("现在栈顶元素为:%d\n",topElem);

    printf("现在栈内元素个数为:%d\n",getStackLen(stack));
////////////////////////////////////////////////////////////////
    printf("本次出栈的元素为:%d\n",pop(stack));

    topElem = getTop(stack);
    printf("现在栈顶元素为:%d\n",topElem);

    printf("现在栈内元素个数为:%d\n",getStackLen(stack));
/////////////////////////////////////////////////////////////////
    printf("本次出栈的元素为:%d\n",pop(stack));

    topElem = getTop(stack);
    printf("现在栈顶元素为:%d\n",topElem);

    printf("现在栈内元素个数为:%d\n",getStackLen(stack));
/////////////////////////////////////////////////////////////////
    printf("本次出栈的元素为:%d\n",pop(stack));

    topElem = getTop(stack);
    printf("现在栈顶元素为:%d\n",topElem);

    printf("现在栈内元素个数为:%d\n",getStackLen(stack));

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值