链队列-数据结构

时间:2021-10-03 10:25:08

链队列

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
using namespace std;
#include "stdlib.h"
#include "windows.h"
#define OK 1
#define ERROR 0
#define M 100
typedef int QElemType;

typedef struct QNOde
{
	QElemType data;
	struct QNOde *next;
}QNode,*QueuePtr;
typedef struct
{
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

int InitQueue(LinkQueue &Q);
int EnQueue(LinkQueue &Q,QElemType e);
int GetHead(LinkQueue Q);
int DeQueue(LinkQueue &Q,QElemType &e);

void f() {
	LinkQueue Q;
	InitQueue(Q);
	QElemType e;
	EnQueue(Q, 2);
	EnQueue(Q, 6);
	EnQueue(Q, 5);
	cout<<"队头元素为:"<<endl<<GetHead(Q)<<endl;
	DeQueue(Q,e);
	cout << "删除值为 "<<e<<" 的头元素后再取队列头元素为:" << endl;
	cout<<GetHead(Q)<<endl;
	system("pause");
}
int main() {
	f();
	return 0;
}

int InitQueue(LinkQueue &Q)
{//构造一个空队列
	Q.front = Q.rear = new QNode;
	Q.front->next = NULL;
	return OK;
}

int EnQueue(LinkQueue & Q, QElemType e)
{//插入元素e为Q的新的队尾元素
	QueuePtr p;
	p = new QNode;
	p->data = e;
	p->next = NULL;
	Q.rear->next = p;
	Q.rear = p;
	return OK;
}

int GetHead(LinkQueue Q)
{//返回Q的队头元素,不修改队头指针
	if(Q.front!=Q.rear)
	return Q.front->next->data;
}

int DeQueue(LinkQueue & Q, QElemType & e)
{//删除Q的头元素,用e返回其值
	if (Q.front == Q.rear)
		return ERROR;
	QueuePtr p;
	p = Q.front->next;
	e = p->data;
	Q.front->next = p->next;
	if (Q.rear == p)
		Q.rear = Q.front;
	delete p;
	return OK;
}