链表实现队列

这次写的还算正规,稍微压缩了一下代码,但是不影响阅读

画个图帮助理解:

F->0->0->0<-R

第一个0不存数据 

 

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int Elementype;//数据类型
//节点结构
typedef struct Node{
    Elementype Element;//数据域
    struct Node * Next;
}NODE,*PNODE;

//    定义队列结构体
typedef struct QNode {
    PNODE Front;//队头
    PNODE Rear;//队尾
} Queue, *PQueue;

void init(PQueue queue)//初始化
{//头尾指向同一内存空间//头结点,不存数据
    queue->Front = queue->Rear = (PNODE)malloc(sizeof(NODE));
    queue->Front->Next = NULL;//头结点指针为空
}

int isEmpty(PQueue queue)//判空·
{
    if(queue->Front == queue->Rear)return 1;
    return 0;
}

void insert(PQueue queue,Elementype data)//入队
{
    PNODE P = (PNODE)malloc(sizeof(NODE));//初始化
    P->Element = data;
    P->Next = NULL;
    queue->Rear->Next = P;//入队
    queue->Rear = P;
}

void delete(PQueue queue,int * val)//出队,用val返回值
{
    if(isEmpty(queue))printf("队空");
    else
    {
        PNODE  P = queue->Front->Next;//前一元素
        *val = P->Element;//记录值
        queue->Front->Next = P->Next;//出队
        //注意一定要加上判断,手动模拟一下就明白了
        if(P==queue->Rear)queue->Rear = queue->Front;
        free(P);//注意释放
        P = NULL;
    }
}

void destroy(PQueue queue)//释放
{
    //从头开始删
    while(queue->Front != NULL)//起临时指针作用,无需再用别的空间
    {
        queue->Rear = queue->Front->Next;
        free(queue->Front);
        queue->Front = queue->Rear;
    }
}
//测试
int main(void)
{
    int i;
    int e;
    Queue a;
    PQueue queue=&a;
    init(queue);
    for(i=0;i<10;i++)
        insert(queue,i);
    while(!isEmpty(queue))//遍历
    {
        delete(queue,&e);
        printf("%d ",e);
    }
    if(isEmpty(queue))printf("1\n");
    delete(queue,&e);
    destroy(queue);
}

 

  • 139
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 29
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兔老大RabbitMQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值