欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素。

程序员文章站 2024-03-21 14:15:16
...

出队的时候一定要注意是不是最后一个元素出队。

//假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点,试编写相
//应的初始化、入队以及出队算法。
#include<stdio.h>
#include<stdlib.h>
typedef enum { ERROR, OK, EMPTY, NOTEMPTY } bool;
typedef int Status;
typedef int ElemType;
typedef struct Node {
	ElemType data;
	struct Node *next;

}Queue, *LinkQueue;
LinkQueue Rear;
bool InitQueue(LinkQueue Q) {
	Q->next = Q;
	Rear = Q;
	return OK;
}

bool JudgeQueue(LinkQueue Q) {
	if (Rear == Q) {
		printf("Queue is Empty\n");
		return EMPTY;
	}
	printf("Queue is not empty\n");
	return NOTEMPTY;
}

bool EnQueue(LinkQueue Q, ElemType e) {
	LinkQueue p;
	p = (LinkQueue)malloc(sizeof(Queue));
	if (p == NULL)
		return ERROR;
	p->data = e;
	p->next = Rear->next;
	Rear->next = p;
	Rear = p;
	return OK;
}

bool DeQueue(LinkQueue Q, ElemType *e) {
	if (Rear == Q) {
		printf("Queue is Empty\n");
		return ERROR;
	}
	LinkQueue p;
	p = Rear->next->next;
	*e = p->data;
	Rear->next->next = p->next;
	if (Rear == p)
		Rear = Q;
	free(p);
	return OK;
}
//测试
int main() {
	LinkQueue Q = NULL;
	Q = (LinkQueue)malloc(sizeof(Queue));
	bool flag;
	flag = InitQueue(Q);
	if (flag == ERROR)
		printf("Init RROR\n");
	else if (flag == OK)
		printf("Init OK\n");

	JudgeQueue(Q);
	ElemType e;
	for (int i = 0; i < 4; i++) {
		printf("请输入:\n");
		scanf_s("%d", &e);
		flag = EnQueue(Q, e);
		if (flag == OK)
			printf("Enter OK\n");
		else
			printf("Enter ERROR\n");
	}
	JudgeQueue(Q);
	for (int i = 0; i < 3; i++) {
		flag = DeQueue(Q, &e);
		if (flag == ERROR) {
			printf("Queue is EmPty\n");
			continue;
		}
		if (flag == OK) {
			printf("%d\n", e);
		}
		JudgeQueue(Q);
	}
	for (int i = 0; i < 4; i++) {
		printf("请输入:\n");
		scanf_s("%d", &e);
		flag = EnQueue(Q, e);
		if (flag == OK)
			printf("Enter OK\n");
		else
			printf("Enter ERROR\n");
	}
	JudgeQueue(Q);
	for (int i = 0; i < 5; i++) {
		flag = DeQueue(Q, &e);
		if (flag == ERROR) {
			printf("Queue is EmPty\n");
			continue;
		}
		if (flag == OK) {
			printf("%d\n", e);
		}
		JudgeQueue(Q);
	}
}


这个写的很好

相关标签: 队列 数据结构