数据结构中链式栈的c语言实现

本文介绍了如何使用C语言实现链式栈的数据结构,包括头文件`sqstack.h`的定义,栈操作函数的实现如`stack_creat`、`stack_empty`、`stack_push`、`stack_pop`等,以及在主函数`test.c`中的应用和`makefile`的编写。通过示例展示了链式栈的基本操作,如入栈、出栈、清空栈等。

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

一.头文件sqstack.h的实现

#ifndef __SQSTACK_H__
#define __SQSTACK_H__

#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct
{
    datatype *data;//这样写能制定认为输入栈大小
    int maxlen;
    int top;
}sqstack;
extern sqstack *stack_creat(int len);
extern int stack_empty(sqstack * s);
extern void stack_clear(sqstack *s);
extern int stack_full(sqstack * s);
extern int stack_push(sqstack *s,datatype value);
extern datatype stack_pop(sqstack *s);
extern datatype stack_top(sqstack *s);
extern void stack_free(sqstack *s);

#endif

二.函数实现sqstack.c的实现

#include "sqstack.h"
sqstack *stack_creat(int len)
{
    sqstack *s;
    if((s=(sqstack *)malloc(sizeof(sqstack))) == NULL)
    {
        printf("malloc failed\n");
        return NULL;
    }
    if((s->data = (datatype *)malloc(sizeof(datatype))) == NULL)
    {
        printf("malloc failed\n");
        return NULL;
    }
    s -> maxlen = len;
    s -> top = -1;
    return s;
}
/*
*@ret:1 empty
*/
int stack_empty(sqstack * s)
{
    return (s->top == -1?1:0);
}
void stack_clear(sqstack *s)
{
    s -> top = -1;
}
int stack_full(sqstack * s)
{
    return (s -> top == s->maxlen - 1?1:0);
}
int stack_push(sqstack *s,datatype value)
{
    if(s->top == s ->maxlen -1)
    {
        printf("stack is full\n");
        return -1;
    }
    s->data[s->top+1] = value;
    s->top++;
    return 1;
}
datatype stack_pop(sqstack *s)
{
    s->top--;
    return s->data[s->top+1];
}
datatype stack_top(sqstack *s)
{
    return (s->data[s->top]);
}

void stack_free(sqstack *s)
{
    free(s->data);
    s->data = NULL;
    free(s);
    s = NULL;
}

三.主函数test.c中实现

#include"sqstack.h"
int main()
{
    int n = 10;
    sqstack *s;
    s = stack_creat(n);
    stack_push(s,10);

    stack_push(s,20);
    stack_push(s,30);
    stack_push(s,40);
    stack_clear(s);
    while(!stack_empty(s))
    {
        printf("%d ",stack_pop(s));
    }
    puts("");

    stack_free(s);
    return 0;
}

四.makefile的实现

CFLAGS=-c -Wall -g             
test:sqstack.o test.o

.PHONY:clean
clean:
        rm *.o test
                               
                               



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值