队列介绍:
队列是一种数据结构,是一种特殊的受限的线性表,只能在头和尾操作,一端入队,一端出队。队列中一般用front(前)表示头结点,用于队列元素的出队,用rear(后)表示尾结点,用于队列添加元素(入队)。队列中储存元素的叫做结点,头节点不储存数据。形象来说,队列就像排队取票,队列前面的人取票离开,新来的在队列后面。
队列的c++实现方式:
有三种:顺序队列,循环队列,链式队列(这里用链式队列)
链式队列运用链表的思想来实现出队入队比较灵活,头节点的地址不变,不用担心队列过小和假溢出的情况
如图:
1.初始化队列
2.入队
(这date写错了,是data)
链表元素间不连续
3.出队(记住队首出队)
由于头结点没有数据,所以以头节点指向的结点为队首
这里只是示意图,实际上要定义一个结点地址和队首结点地址相同,便于释放空间。而且当
front->next==rear时,没有下一个结点,直接将rear=front,并释放空间。
实现代码如下:
#include<iostream>
#define Status int
#define QElemType int
using namespace std;
//链队结点数据结构
typedef struct Qnode {
QElemType data;//数据域
struct Qnode* next;//指针域
}Qnode,*queueptr;
typedef struct LinkQueue {
struct Qnode* front;
struct Qnode* rear;//front指向队头,rear指向队尾
}LinkQueue;
//**************操作函数****************//
Status initqueue(LinkQueue& Q) {
Q.front = Q.rear = new Qnode;
Q.rear->next = NULL;
return 1;
}//初始化队列
Status EnQueue(LinkQueue& Q, QElemType e) {
Qnode* p;
p = new Qnode;//生成新结点
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return 1;
}//入队,队尾添加
bool DeQueue(LinkQueue& Q, QElemType &e) {
queueptr p;
if (Q.front == Q.rear)
return false;
e = Q.front->next->data;
p = Q.front->next;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return true;
}//出队,队头删除
//*******功能操作*******//
void menu(){
printf("1.入队 2.出队 3.结束");
}
void EnterToQueue(LinkQueue& Q) {
int n; QElemType e; int flag;
printf("输入入队元素个数:\n");
cin >> n;
for (int i = 0; i < n; i++) {
printf("输入第%d个入队元素\n", i + 1);
cin >> e;
flag=EnQueue(Q, e);
if (flag)
printf("%d已入队\n",e);
}
}//入队操作
void DeleteFromQueue(LinkQueue Q) {
int n; QElemType e; int flag;
printf("输入出队个数:\n");
cin >> n;
for (int i = 0; i < n; i++) {
flag = DeQueue(Q, e);
if (flag) {
printf("%d已出队\n",e);
}
else {
printf("队已空!\n");
}
}
}//出队操作
int main() {
LinkQueue Q;
int choice;
initqueue(Q);
while (1) {
menu();
cout << "\n输入操作编号:";
cin >> choice;
if (choice == 3)
break;
switch (choice) {
case 1:EnterToQueue(Q); break;
case 2:DeleteFromQueue(Q); break;
default:printf("超出范围!\n");
}
}
return 0;
}
有误请指正