数据结构 05 - 栈 链式存储

  栈的运用很广泛,熟知的比如C语言程序运行中的局部变量就是存在栈区,当前模块运行完后自动出栈(释放)。栈的特点是先进后出(FILO),链式栈采用线性结构,链式存储的方式进行实现。
  下面代码linkstack.c含链式栈的相关操作函数,main.c测试功能的实现与否。
运行结果:
入栈顺序为9 8 7 6 5 4 3 2 1 0,见main.c
在这里插入图片描述

/*
linkstack.c
*/
#include "linkstack.h"

//创建结点
Linkstack *create_linkstack()
{
    Linkstack *s = (Linkstack *)malloc(sizeof(Linkstack));
    if(NULL == s){//申请空间失败
        printf("malloc failed!\n");
        return NULL;
    }
    
    s->data = -1;
    s->next = NULL;

    return s;
}

//判空
int linkstack_is_empty(Linkstack *s)
{
    
    if(s->next == NULL){//为空
        return 1;
    }
    else{
        return 0;
    }
}

//入栈
void linkstack_push(Linkstack *s,data_t data)
{
    Linkstack *p = create_linkstack();
    p->data = data;

    p->next = s->next;
    s->next = p;
}

//出栈
void linkstack_pop(Linkstack *s,data_t *data)
{
    if(linkstack_is_empty(s)){//为空
        printf("linkstack is empty!\n");
        return;
    }
    
    Linkstack *p = s->next;
    *data = p->data;

    s->next = p->next;
    free(p);
}
/*
linkstack.h
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef __LINKSTACK__
#define __LINKSTACK__

typedef int data_t;
typedef struct linkstack{
    data_t data;
    struct linkstack* next;
}Linkstack;

//创建结点
Linkstack *create_linkstack();

//判空
int linkstack_is_empty(Linkstack *s);

//入栈
void linkstack_push(Linkstack *s,data_t data);

//出栈
void linkstack_pop(Linkstack *s,data_t *data);
#endif
/*
main.c
*/
#include "linkstack.h"

int main()
{
    Linkstack *s = create_linkstack();
    int n = 10;
    //入栈顺序 9 8 7 6 5 4 3 2 1 0
    while(n--){
        linkstack_push(s,n);
    }
    
    printf("出栈顺序: ");
    int i,data;
    for(i = 0; i < 10; i++){
        linkstack_pop(s,&data);
        printf("%d ",data);
    }
    printf("\n");

    return 0;
}
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值