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

[栈与队列] 3.28 队列 - 带头结点的循环链

程序员文章站 2022-03-08 08:18:55
...

题目来源:严蔚敏《数据结构》C语言版本习题册 3.28

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

#ifndef BASE
#define BASE
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int bool;
#endif

// 实现:队列
// 数据结构:循环链表(带头结点)
// 结构体:只设置一个指针指向队尾元素结点(不设头指针)

typedef int ElemType;
typedef struct NodeType{
	ElemType data;
	struct NodeType *next;
}QNode, *QPtr;
typedef struct{
	QPtr rear;
}Queue;

Status InitQueue(Queue *pQ) {
	QNode *newNode;
	//头结点
	newNode = (QNode *)malloc(sizeof(QNode));
	if (!newNode) exit(OVERFLOW);
	newNode->next = newNode; //指向自己,循环链表
	pQ->rear = newNode; //尾指针指向头结点
	return OK;
}

Status EnQueue(Queue *pQ, ElemType e) {
	QNode *newNode;
	newNode = (QNode *)malloc(sizeof(QNode));
	if (!newNode) exit(OVERFLOW);
	newNode->data = e;
	newNode->next = pQ->rear->next;
	pQ->rear->next = newNode;
	pQ->rear = newNode;
	return OK;
}

Status DeQueue(Queue *pQ,ElemType *e) {
	QNode *tmp, *top;
	
	if (pQ->rear->next==pQ->rear) return ERROR; //空
	top = pQ->rear->next; //头结点
	tmp = top->next; //得到队列的第一个元素
	*e = tmp->data; //赋值
	//删除队列的第一个元素
	top->next = tmp->next;
	free(tmp);
	//如果队列又为空,则需要改变尾指针的指向
	if (top->next==top) pQ->rear=top;
	return OK;
}

Status Debug(Queue Q, void (*Visit)(ElemType e)) {
	QNode *top,*tmp;
	printf("----------------\n");
	printf("rear指向:%d\n", Q.rear->data); //debug
	top = Q.rear->next;
	tmp = top;
	do {
		Visit(tmp->data);
		tmp=tmp->next;
	}while(tmp!=top);
	printf("\n----------------\n");
	return OK;
}

void visit(ElemType e) {
	printf("%d\t", e);
}

int main() {
	int c;
	int tmp;
	Queue Q;
	InitQueue(&Q);
	Debug(Q, &visit);
	while (1) {
		scanf("%d", &c);
		switch(c) {
		case 1:scanf("%d",&tmp);EnQueue(&Q, tmp);Debug(Q,&visit);break;
		case 2:DeQueue(&Q, &tmp);printf("抛出%d\n", tmp);Debug(Q,&visit);break;
		}
	}
	return 0;
}
相关标签: 队列