3_2_链式队列的基本操作的实现

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



typedef struct  LinkNode//链式队列节点
{
	int data;    //存放队列中元素
	struct LinkNode *next;
}LinkNode;

typedef struct //链式队列
{
        LinkNode *front;//队列的队头指针
        LinkNode *rear;//队列的队尾指针
}LinkQueue;

//链式队列的初始化
void InitQueue(LinkQueue *Q)
{
   (*Q).front = (*Q).rear = (LinkNode*)malloc(sizeof(LinkNode));
   (*Q).front -> next = NULL;
	return true;
}

//判断队列是否为空
bool QueueEmpty(LinkQueue *Q)
{
    if((*Q).front == (*Q).rear)
    {
//        printf("当前队列为空\n");
        return true;//队列空
    }
    else
    {
//        printf("当前队列非空\n");
        return false;//队列非空
    }
}

//入队
void EnQueue(LinkQueue *Q, int e)
{
    LinkNode *newnode = (LinkNode*)malloc(sizeof(LinkNode));//创建新的结点
    newnode->data = e;//将入队的数据赋值给结点的data
    newnode->next = NULL;//将结点插入到链尾
    (*Q).rear -> next = newnode;
    (*Q).rear = newnode;
}

//出队
bool DeQueue(LinkQueue *Q, int *e)
{
    if(QueueEmpty(Q)==1)
    {
        printf("队列为空,没有元素可以出队\n");
        return false;
    }
    else
    {
        LinkNode *p = (*Q).front->next;
        *e = p -> data;//将出队元素的值给e
        (*Q).front -> next = p -> next;
        if ((*Q).rear == p)//如果p为队列中唯一结点,删除后变空需要单独处理
        {
            (*Q).rear = (*Q).front;
        }
        free(p);
        return true;
    }
}



 int main()
 {
	LinkQueue Q1;
    int e = -1;
	InitQueue(&Q1);
	DeQueue(&Q1, &e);
	EnQueue(&Q1, 1);
	EnQueue(&Q1, 2);
	EnQueue(&Q1, 3);
	EnQueue(&Q1, 4);
	EnQueue(&Q1, 5);
	EnQueue(&Q1, 6);
    DeQueue(&Q1, &e);
	printf("出队元素为%d\n", e);
    DeQueue(&Q1, &e);
	printf("出队元素为%d\n", e);
	return 0;
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值