C语言实现队列(链表实现)

队列 (Queue) :也是运算受限的线性表。是一种先进先出 (First In First Out ,简称 FIFO) 的线性表。只允许在表的一端进行插入,而在另一端进行删除。 
队首 (front) :允许进行删除的一端称为队首。 

 

队尾 (rear) :允许进行插入的一端称为队尾。

 

代码:

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

//定义节点
typedef struct node{
    char data;
    struct node * next;
}node;

//定义队列(保存队首和队尾指针)
typedef struct queue_link{
    node * front;
    node * rear;
}que;

//初始化队列
que * InitQueue()
{
    que * q = (que*)malloc(sizeof(que));
    q->front = q->rear = NULL;
    return q;
}

//判断队列是否为空
int EmptyQueue(que * q)
{
    return q->front == NULL;
}

//入队
void InsertQueue(que *q, char data)
{
    node * n = (node *)malloc(sizeof(node));
    if(n == NULL)//内存分配失败
        return ;
    n->data = data;
    n->next = NULL;//尾插法,插入元素指向空
    if(q->rear == NULL)
    {
        q->front = n;
        q->rear = n;
    }
    else{
       q->rear->next = n;//让n成为当前的尾部节点下一节点
        q->rear= n;//尾部指针指向n
    }

}

//出队(删除队首元素)
void DeleteQueue(que *q)
{
    node * n = q->front;
    if(q->front == NULL)//判断队列是否为空
        return ;
    if(q->front == q->rear)//是否只有一个元素
    {
        q->front = NULL;
        q->rear = NULL;
    }
    else{
        q->front = q->front->next;
        free(n);
    }

}

//打印队列
void Display(que * q)
{
    node * n = (node *)malloc(sizeof(node));
    n = q->front;
    if(n == NULL)
    {
        return ;//队列为空
    }
    while(n != NULL)
    {
        printf("%c ",n->data);
        n = n->next;
    }
    printf("\n");
}
int main()
{
    int i=5,j=5;
    que * q;
    q = InitQueue();
    printf("开始入队:\n");
    while(i--)
    {
        printf("元素%c入队,队列为:",'A'+i);
        InsertQueue(q,'A'+i);
        Display(q);
    }
    printf("开始出队:\n");
    while(j--)
    {
        printf("第%d个元素出队,队列为:",5-j);
        DeleteQueue(q);
        Display(q);
    }
    printf("\n");
    return 0;
}

 

 

 

 

 

  • 25
    点赞
  • 148
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值