数据结构(C语言第二版)链式队列的创建及基本操作的实现

        要创建一个队列,首先要对队列的定义完全掌握,队列是一种受限制的线形表,只能表头出队列,表尾进队列。那么我们在创建队列时,要牢牢把握这一特性,每新增一个元素进队列时,队尾指针都要向后移一位,而队首指针不动指向第一个元素,以此类推。

        注意:在第一个元素进队列时,队首指针和队尾指针都要指向第一个元素。

以下是代码实现:

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

//链式队列
typedef struct Queue{
    int data;
    struct Queue *top;
    struct Queue *base;
}Queue;

//初始化
void InitQueue(Queue *p){
    p->top=p->base=NULL;
}

//进队列
void EnQueue(Queue *l,int elem){
    Queue *p=(Queue*)malloc(sizeof(Queue));
    if (p==NULL){
        printf("分配失败");
        return;
    }
    p->data=elem;
    p->base=NULL;
    if (l->top==NULL){
        l->top=l->base=p;
    } else{
        l->base->base=p;
        l->base=p;
    }
}

//出队列
void DeQueue(Queue *l){
    if (l->top==NULL && l->base==NULL){
        printf("出队列失败");
        return;
    } else{
        Queue *temp=l->top;
        l->top=l->top->base;
        free(temp);
    }
}

//取队列第一个元素
void GetHead(Queue *l){
    if (l->top==NULL && l->base==NULL){
        printf("队列为空,取值失败");
        return;
    } else{
        printf("队首元素为:%d\n",l->top->data);
    }
}

//队列长度
void LengthQueue(Queue *l){
    if (l->top==NULL && l->base==NULL){
        printf("队列为空");
        return;
    } else{
        int count=0;
        Queue *temp=l->top;
        while (temp!=NULL){
            count++;
           temp=temp->base;
        }
        printf("队列长度为:%d\n",count);
    }
}

//遍历队列元素,分别输出
void PrintQueue(Queue *l){
    if (l->top==NULL && l->base==NULL){
        printf("队列为空");
        return;
    } else{
        Queue *temp=l->top;
        printf("队列中有元素:");
        while (temp!=NULL){
            printf("%d\t",temp->data);
            temp=temp->base;
        }
    }
}
int main(){
    Queue p;
    InitQueue(&p);
    EnQueue(&p,10);
    EnQueue(&p,80);
    EnQueue(&p,90);
    GetHead(&p);
    LengthQueue(&p);
    PrintQueue(&p);
}

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值