队列的链式存储结构与操作方法

#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED

typedef int ElemType;
typedef struct SingleNode
{
	ElemType data;   //值域
    struct SingleNode* next;//链接指针域
}Node;
typedef struct linkQueue
{
	Node* front;
	Node* rear;
}Queue;

/******************************/
//初始化链表
void initQueue(Queue* Q, int ms)
{
	Q->front = Q->rear = NULL;
}

/**********************************/
//向链队中插入一个元素
void enQueue(Queue* Q, ElemType item)
{
	Node* r = malloc(sizeof(Node));
	r->data = item;
	r->next = NULL;
	if (Q->rear == NULL)//判断链队是否为空
	{
		Q->front = Q->rear = r;
	}
	else
	{
		Q->rear->next = r;
		Q->rear = Q->rear->next;
	}
}
/********************************************************/
//从队列中删除一个元素
ElemType outQueue(Queue* Q)
{
	if (Q->front == NULL)
	{
		printf("链队为空,无法删除,退出运行!\n");
		exit(1);
	}
	else
	{
		ElemType temp = Q->front->data;
		Node* p = Q->front;
		Q->front = p->next;

		if (Q->front == NULL)
		{
			Q->rear = NULL;
		}
		free(p);

		return temp;
	}
}
/*******************************************************/
//读取队首元素
ElemType peekQueue(Queue* Q)
{
	if (Q->front==NULL)
	{
		printf("链队为空!,无法删除,退出运行!\n");
		exit(1);
	}
	return Q->front->data;
}
/****************************************************/
//检查链队是否为空
int emptyQueue(Queue* Q)
{
	return Q->front == NULL;
}
/***************************************************/
//清除链队中所有元素,使之变为空队
void clearQueue(Queue* Q)
{
	Node* p = Q->front;
	while (p != NULL)
	{
		Q->front = Q->front->next;
		free(p);
		p = Q->front;
	}
	Q->rear = NULL;
}
#endif // !QUEUE_H_INCLUDED
#pragma once
在这里插入代码片
#include <stdlib.h>
#include <stdio.h>
#include "Queue.h"
int main()
{
	int i, x = 12;
	Queue d, * q = &d;
	initQueue(q, 1);
	enQueue(q, 35);
	enQueue(q, 2 * x + 3);
	enQueue(q, -16);
	printf("%d ", peekQueue(q));
	printf("%d\n", outQueue(q));
	for (i = 0; i < 30; i += 2)
	{
		enQueue(q,i);
	}
	while (!emptyQueue(q))
	{
		printf("%d ", outQueue(q));
	}
	printf("\n");
	clearQueue(q);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值