数据结构--链队列

/*队列没完全看懂*/
#include <stdio.h>
#include <stdlib.h>
#define Datatype int
//定义节点结构
typedef struct node{
    Datatype data;
    struct node *next;
}QueueNode;
//定义头节点
typedef struct{
    QueueNode *front;
    QueueNode *rear;
}LinkQueue;

//初始化链队列,头节点置空
void InitQueue(LinkQueue *Q)
{
    Q->front = Q->rear = NULL;
}

//判断链队列是否为空
int QueueEmpty(LinkQueue *Q)
{
    return(Q->front == NULL && Q->rear == NULL);
}

//入队
void EnLinkQueue(LinkQueue *Q, Datatype v)
{
    QueueNode *p;
    p = (QueueNode *)malloc(sizeof(QueueNode));//为新的节点分配空间
    p->data = v;
    p->next = NULL;
    if(QueueEmpty(Q))
        Q->front = Q->rear = p;
    else
    {
        Q->rear->next = p;  //将新的节点连接到队列
        Q->rear = p;             //指向队列尾
    }
}

//出队
Datatype DeLinkQueue(LinkQueue *Q)
{
    Datatype i;
    QueueNode *s;
    if(QueueEmpty(Q))     //判断队列是否为空
        printf("Error,the linkqueue is empty!");
    s = Q->front;
    i = s->data;
    if(Q->front == Q->rear)   //判断队列是否只有一个节点
        Q->front = Q->rear = NULL;
    else
        Q->front = s->next;
    free(s);
    return i;

}

//读取队列头元素,不改变队列状态
Datatype ReadLinkQueue(LinkQueue *Q)
{
    Datatype i;
    if(QueueEmpty(Q))     //判断队列是否为空
        printf("Error,the linkqueue is empty!");
    i = Q->front->data;
    return i;
}

int main()
{
    LinkQueue Q;
    Datatype i = 1;
    InitQueue(&Q);
    while(i<=6)
    {
        EnLinkQueue(&Q,i);      //将1-6入队
        i++;
    }
    printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));
    printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));
    printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));
    printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));

    EnLinkQueue(&Q,9);
    printf("The all number of the linkqueue:\n");
    while(!QueueEmpty(&Q))
        printf("%d\t",DeLinkQueue(&Q));         //输出队列中所有数据

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值