博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
小练习 - 基于链表的栈和队列
阅读量:4206 次
发布时间:2019-05-26

本文共 1996 字,大约阅读时间需要 6 分钟。

随手练下基本的数据结构,基于链表实现一个动态大小的栈和队列,最基本简单的数据结构要注意各种边界场景。基于链表实现,频繁增删调用mallc会带来一定开销,实际使用要看情况来定。

基于链表的栈

typedef struct _node {    int data;    struct _node* next;}node;typedef struct _stack {    node *top;    node *bottom;    size_t num;}stack;void init(stack *s){    s->top = NULL;    s->bottom = NULL;    s->num = 0;}int is_empty(stack *s){    return s->num == 0;}int top(stack *s){    if (!is_empty(s)) {        return s->top->data;    } else {        printf("run top fail, stack is empty!\n");        return 0;    }}void pop(stack *s){    node *tmp;    if (!is_empty(s)) {        tmp = s->top;        s->top = tmp->next;        free(tmp);        s->num--;        if (is_empty(s)) {            s->bottom = NULL;        }    } else {        printf("run pop fail, stack is empty!\n");    }}void push(stack *s, int data){    node *pdata = (node *)malloc(sizeof(node));    pdata->data = data;    if (is_empty(s)) {        s->top = pdata;        s->bottom = pdata;        pdata->next = NULL;    } else {        pdata->next = s->top;        s->top = pdata;    }    s->num++;}void clear_stack(stack *s){    while (!is_empty(s)) {        pop(s);    }}

基于链表的队列

typedef struct _node {    int data;    struct _node* next;}node;typedef struct _queue {    node *front;    node *rear;    size_t num;}queue;int is_empty(queue *q){    return q->num == 0;}void push(queue *q, int val){    node *pnode = (node*)malloc(sizeof(node));    pnode->data = val;    pnode->next = NULL;    if (q->rear) {        q->rear->next = pnode;    } else {        q->front = pnode;    }    q->rear = pnode;    q->num++;}void pop(queue *q){    if (!is_empty(q)) {        node *pnode = q->front;        q->front = q->front->next;        free(pnode);        q->num--;        if (is_empty(q)) {            q->rear = NULL;        }    } else {        printf("error: pop the empty queue!");    }}void init(queue *q){    q->front = NULL;    q->rear = NULL;    q->num = 0;}void clear_queue(queue *q){    while (!is_empty(q)) {        pop(q);    }}

转载地址:http://vfqli.baihongyu.com/

你可能感兴趣的文章
DataStage(ETL)技术总结 -- 介绍篇(转载)
查看>>
Greenplum技术浅析--vs oracle RAC
查看>>
框架一
查看>>
Oracle-内存管理解读
查看>>
Oracle-PFILE和SPFILE解读
查看>>
leetcode 13: Roman to Integer
查看>>
ubuntu的php7与apache2的环境搭建
查看>>
MySQL修改root密码的4种方法
查看>>
CentOS Apache 环境+php,解决php直接输出源码
查看>>
python 安装scipy 报错:Microsoft Visual C++ 14.0 is required
查看>>
python 报错Microsoft Visual C++ 14.0 is required
查看>>
requests.exceptions.TooManyRedirects: Exceeded 30 redirects.
查看>>
爬取《战狼2》电影短评论,生成图云
查看>>
linux 操作命令: cp
查看>>
adb 命令2
查看>>
matplotlib中文坐标轴和标题显示
查看>>
使用K-S检验一个数列是否服从正态分布、两个数列是否服从相同的分布
查看>>
网络传输层在网络中的地位
查看>>
网络中进程通信的标识
查看>>
TCP与UDP的区别
查看>>