c++实现队列基本操作

c++实现队列基本操作,进队,出队,遍历队列

2019-11-26

#include <iostream>
using namespace std;

typedef int DataType;
#define Node ElemType

class Node
{
public:
	DataType data;
	ElemType *next;
};

class QueueLinkList 
{
public:
	QueueLinkList();				//初始化队列
	~QueueLinkList();				//摧毁队列
	int IsEmpty();					//判断队列是否为空
	void Enqueue(DataType data);	//入队
	void Dequeue();					//出对
	void PrintfQueue();				//打印队列
private:
	ElemType *front;
	ElemType *rear;
};

//初始化队列
QueueLinkList::QueueLinkList()
{
	front = new ElemType;
	front->data = 0;
	front->next = NULL;
	rear = front;
}

//摧毁队列
QueueLinkList::~QueueLinkList()
{
	delete front;
}

判断队列是否为空
int QueueLinkList::IsEmpty()
{
	return front->next == NULL;
}

//入队
void QueueLinkList::Enqueue(DataType data)
{
	ElemType *newNode = new ElemType;
	newNode->data = data;
	newNode->next = NULL;
	rear->next = newNode;
	rear = newNode;
}

//出队
void QueueLinkList::Dequeue()
{
	if (front->next == NULL)
	{
		cout << "队为空" << endl;
		return;
	}
	ElemType *ptemp = front->next;
	front->next = ptemp->next;
	delete ptemp;
}

//遍历队列
void QueueLinkList::PrintfQueue()
{
	ElemType *p = front;
	if (front->next == NULL)
	{
		cout << "队为空" << endl;
		return;
	}
	while (p->next != NULL)
	{
		p = p->next;
		cout << p->data << " ";
	}
	cout << endl;
}

//测试函数
int main()
{
	QueueLinkList q;
	int i;
	cout << "1.判断队是否为空   2.入队   3.出队   4.打印队   0.退出" << endl;
	do
	{
		cout << "请输入要执行的操作:";
		cin >> i;
		switch (i)
		{
		case 1:
			if (q.IsEmpty() == 1)
				cout << "空队" << endl;
			else
			{
				cout << "不是空队" << endl;
			}
			break;
		case 2:
			int n;
			cout << "请输入要入队的值:";
			cin >> n;
			q.Enqueue(n);
			break;
		case 3:
			q.Dequeue();
			break;
		case 4:
			cout << "打印队列" << endl;
			q.PrintfQueue();
			break;
		default:
			cout << "输入的操作值错误" << endl;
			break;
		}
	} while (i != 0);
	system("pause");
	return 0;
}

  • 7
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值