队列------链式存储

1.

数据抽象:

typedef int QElemType;

typedef struct QNode    //节点结构
{
	QElemType data;
	struct QNode *next;
}QNode,*QueuePtr;

typedef struct
{
	QueuePtr front, rear;    //队头  队尾
}LinkQueue;

 入队:

//入队
void InQueue(LinkQueue &Q, QElemType e)
{
	//构造节点
	QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
	if (!s)          //存储失败
		printf("存储失败\n");

	s->data = e;
	s->next = NULL;

	if (IsEmpty(Q)) {
		Q.front = Q.rear = s;
		printf("kong");
	}

	Q.rear->next = s;  //把s赋给队尾的后继
	Q.rear = s;       //把s设为队尾节点
}

出队:

//出队
void DeQueue(LinkQueue &Q, QElemType &e)
{
	QueuePtr p;
	if (Q.front == Q.rear)
		printf("没有元素出队\n");
	p = Q.front->next; /*将欲'时除的队头给点暂存给p.,儿上闺中①*/
	e = p->data;
	Q.front->next = p->next; /*将原队头给点后继p->next 赋值给头给点后继. */

	if (Q.rear == p)  /* 若队头是队尾,则倒自最后将rear 指向头量点点,几上圈中③*/
		Q.rear = Q.front;
	free(p);
	printf("出队:%d\n", e);
}

全部代码:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
using namespace std;

typedef int QElemType;

typedef struct QNode    //节点结构
{
	QElemType data;
	struct QNode *next;
}QNode,*QueuePtr;

typedef struct
{
	QueuePtr front, rear;    //队头  队尾
}LinkQueue;


//队列的初始化
void InitQueue(LinkQueue &Q)
{
	Q.front = NULL;
	Q.rear = NULL;
}

//判断队列是否为空
bool IsEmpty(LinkQueue Q)
{
	return Q.front = NULL;
}

//入队
void InQueue(LinkQueue &Q, QElemType e)
{
	//构造节点
	QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
	if (!s)          //存储失败
		printf("存储失败\n");

	s->data = e;
	s->next = NULL;

	if (IsEmpty(Q)) {
		Q.front = Q.rear = s;
		printf("kong");
	}

	Q.rear->next = s;  //把s赋给队尾的后继
	Q.rear = s;       //把s设为队尾节点
}

//出队
void DeQueue(LinkQueue &Q, QElemType &e)
{
	QueuePtr p;
	if (Q.front == Q.rear)
		printf("没有元素出队\n");
	p = Q.front->next; /*将欲'时除的队头给点暂存给p.,儿上闺中①*/
	e = p->data;
	Q.front->next = p->next; /*将原队头给点后继p->next 赋值给头给点后继. */

	if (Q.rear == p)  /* 若队头是队尾,则倒自最后将rear 指向头量点点,几上圈中③*/
		Q.rear = Q.front;
	free(p);
	printf("出队:%d\n", e);
}


//利用入队操作创建一个队列,他拥有n个元素
void createQueue(LinkQueue &Q, int n) {
	int i = 0;
	printf("请输入%d个字符元素:\n", n);
	while (i < n) {
		int dataTmp;
		scanf("%d", &dataTmp);
		InQueue(Q, dataTmp);
		i++;
		getchar();//吃掉换行符
	}
}

//打印
void PrintQueue(LinkQueue Q)
{
	QueuePtr p = Q.front;
	while (p != NULL)
	{
		printf("%d\n", p->data);
		p = p->next;
	}
}

void main()
{
	LinkQueue Q;

	//初始化
	//初始化
	InitQueue(Q);
	if (IsEmpty(Q))
		printf("队列此时为空\n");
	else
		printf("队列此时不为空\n");


	//入队列
	printf("入队列\n...........\n");
	InQueue(Q, 1);
	InQueue(Q, 2);
	InQueue(Q, 3);
	InQueue(Q, 4);

	QElemType e;
	//出队列
	printf("出队列\n............\n");
	DeQueue(Q, e);
	printf("出元素%d\n", e);
	DeQueue(Q, e);
	printf("出元素%d\n", e);

	/*打印*/
	printf("打印队列元素\n");
	PrintQueue(Q);

	system("pause");

}

参考资料:

  1. 《大话数据结构》

猜你喜欢

转载自blog.csdn.net/qq_39503189/article/details/81533279