线性表之栈的链式存储实现

栈的链式存储也称为链栈,和链表的存储原理一样,都可以通闲散空间来存储元素,用指针来建立各节点之间的逻辑关系。同顺序栈,链表的插入,删除操作也只能在栈顶进行。

链栈的C语言实现:(codeblocks完美运行)


#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
        int data;                //数据域
        struct Node *next;       //指向下一个节点的指针
}pNode;

typedef struct Stack
{
        pNode *top;              //指向栈顶元素的指针
        int size;                //栈的大小
}linkstack;


//初始化链栈
linkstack* create()
{
    linkstack *stack = (linkstack*)malloc(sizeof(linkstack));
    if(stack != NULL)
    {
        stack->top = NULL;
        stack->size = 0;
    }
    return stack;
}

//判断栈是否为空,是返回1,不是返回0
int IsEmpty(linkstack *stack)
{
    if(stack->top == NULL || stack->size == 0)
        return 1;
    return 0;
}

//获得链栈大小
int getsize(linkstack *stack)
{
    return stack->size;
}

//取得栈顶元素
pNode* getTop(linkstack *stack)
{
    if(stack->size != 0)
        return stack->top;
    return NULL;
}

//入栈
int Push(linkstack *stack,int val)
{
    pNode *node = (pNode*)malloc(sizeof(pNode));
    if(node != NULL)
    {
        node->data = val;
        node->next = getTop(stack);     //新元素节点指向下一个节点,链式实现
        stack->top = node;              //top指向新节点
        stack->size++;                  //栈的大小加1
    }
    return 1;
}

//出栈
pNode* Pop(linkstack *stack)
{
    if(IsEmpty(stack))
    {
        return NULL;
    }
    pNode *node = stack->top;       //node指向栈顶
    stack->top = stack->top->next;  //top指向下一个元素
    stack->size--;                  //链栈长度减少
    return node;
}

//销毁栈
void Destroy(linkstack *stack)
{
    if(IsEmpty(stack))
    {
        free(stack);
        printf("\n链表已为空,无需再进行销毁!\n");
    }
    //如果链栈中数据不为空,就需要把栈中的节点都删除再释放
    else
    {
        while(stack->size >0)
        {
            pNode *ptr;
            ptr = Pop(stack);
            free(ptr);
        }
        printf("链栈消除成功!\n");
    }
}

int main()
{
    srand((unsigned)time(0));
    linkstack *stack = NULL;
    stack = create();
    int i;
    for(i=0;i<30;i++)
        Push(stack,rand()%100);
    if(IsEmpty(stack))
        printf("链栈为空!\n");
    else
    {
        printf("链栈不为空!\n");
        printf("栈顶元素为:%d",*((int*)getTop(stack)));      //返回的是pNode类型指针,所以要强转成int型
        printf("链栈大小为:%d",getsize(stack));
        for(i=0;i<30;i++)
        {
            if(i%6==0)          //每打印6个就换行
                printf("\n");
            printf("%3d  ",*((int*)Pop(stack)));            //返回的是pNode类型指针,所以要强转成int型
        }
    }

    Destroy(stack);//销毁链

    return 0;
}



运行界面:



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值