数据结构:队列的链式存储(带头结点)

数据结构:队列的链式存储(带头结点)

1.结点的数据结构
2.队列的数据结构
3.初始化
4.入队操作
5.出队操作
6.判空操作
7.读队头元素
8.测试
9.输出结果

所用编译器:Visual Studio Code 1.42.1 C++环境

#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
//结点的数据结构
typedef struct LinkNode{
    Elemtype data;
    struct LinkNode *next;
}LinkNode;
//队列的数据结构
typedef struct{
    LinkNode *front,*rear;
    int length;     //用于记录队列的长度
}LinkQueue;
//初始化
void InitQueue(LinkQueue &Q){
    Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode));
    Q.front->next=NULL;
    Q.length=0;
}
//入队操作
bool EnQueue(LinkQueue &Q,Elemtype x){
    LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
    s->data=x;
    s->next=NULL;
    Q.rear->next=s;
    Q.rear=s;
    Q.length++;
    return true;
}
//出队操作
bool DeQueue(LinkQueue &Q,Elemtype &x){
    if(Q.front==Q.rear)
        return false;
    LinkNode *p=Q.front->next;
    x=p->data;
    Q.front->next=p->next;
    if(Q.rear==p)
        Q.rear=Q.front;
    free(p);
    Q.length--;
    return true;
}
//判空操作
bool IsEmpty(LinkQueue Q){
    return(Q.front==Q.rear);
}
//读队头元素
bool GetHead(LinkQueue Q,Elemtype &x){
    if(Q.front==Q.rear)
        return false;
    x=Q.front->next->data;
    return true;
}
//测试
int main(){
    LinkQueue Q;
    InitQueue(Q);

    Elemtype a,b,c;

    //入队几个元素并打印队列长度
    EnQueue(Q,3);
    EnQueue(Q,5);
    EnQueue(Q,9);
    EnQueue(Q,6);
    printf("Q.length=%d\n",Q.length);

    //出队几个元素并打印
    DeQueue(Q,a);
    DeQueue(Q,b);
    printf("a=%d\n",a);
    printf("b=%d\n",b);

    //读当前队头元素并打印
    GetHead(Q,c);
    printf("c=%d\n",c);

    //判断当前队列是否为空
    if(IsEmpty(Q))
        printf("当前队列为空\n");
    else
        printf("当前队列不为空\n");
    
    //将剩余元素删除后再判空
    DeQueue(Q,a);
    DeQueue(Q,b);
    if(IsEmpty(Q))
        printf("当前队列为空\n");
    else
        printf("当前队列不为空\n");
}
//输出结果
Q.length=4
a=3
b=5
c=9
当前队列不为空
当前队列为空
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值