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

队列实现

程序员文章站 2022-07-14 12:25:31
...
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef char QueueElemType;

typedef struct LinkQueueNode
{
	QueueElemType data;
	struct LinkQueueNode *next;
}LinkQueueNode;

typedef struct LinkQueue
{
	LinkQueueNode *front;
	LinkQueueNode *rear;
}LinkQueue;

int EnterQueue(LinkQueue *Q, QueueElemType x)
{
	LinkQueueNode *NewNode;
	NewNode = (LinkQueueNode *)malloc(sizeof(LinkQueueNode));
	if(NewNode != NULL)
	{
		NewNode->data = x;
		NewNode->next = NULL;
		Q->rear->next = NewNode;
		Q->rear = NewNode;
		return true;
	}
	else
	{
		return false;
	}
}

int DeleteQueue(LinkQueue *Q, QueueElemType *x)
{
	LinkQueueNode *p;
	if(Q->front == Q->rear)
	{
		return false;
	}
	p = Q->front->next;
	Q->front->next = p->next;
	if(Q->rear == p)
	{
		Q->rear = Q->front;
	}
	*x = p->data;
	free(p);
	return true;
}

int scan()
{
	int n;
	cout << "1、入队       2、出队" << endl;
	cin >> n;
	return n;
}

int main()
{
	int quit = 0;
	QueueElemType x;
	LinkQueue *queue = (LinkQueue *)malloc(sizeof(LinkQueue));

	queue->front = (LinkQueueNode *)malloc(sizeof(LinkQueueNode));
	queue->rear = queue->front;
	queue->front->next = NULL;
	while(!quit)
	{
		switch(scan())
		{
		case 1 :  cin >> x; EnterQueue(queue, x); break;
		case 2 : if(DeleteQueue(queue, &x) == true) cout << x << "元素已出队" << endl; else cout << "队列为空,请输入要入队的元素" << endl; break;
		default : quit = 1;
		}
	}
	return 0;
}

转载于:https://www.cnblogs.com/lgh1992314/archive/2013/04/03/5835142.html