队列是一种特殊的线性表,在这种线性表中,删除运算限定在表的一段进行,而插入运算限定在表的另一端进行,通常,约定把允许插入的一端称为队尾,把允许删除的一端称为队首。队列进出的原则是先进队的先出队,即先进先出原则。队列在计算机程序设计中经常被用到,如Windows操作系统的消息队列。
队列可以采用链式或顺序存储结构来描述,本文采用链式结构来进行表达。由于队列需要在队首以及队尾进行删除和插入操作,所以需要设置两个指针来表示队列,通常队尾指针指向最后进入队列的元素,为了便于表示空队列,专门设置了一个头结点,当队列为空时,头指针和尾指针均指向头结点。
本文示例中的函数功能包括队列的创建、入队、出队、打印、统计队列长度。
#include <iostream>
using namespace std;
struct node //队列的节点
{
int data;
struct node *next;
};
struct linkQueue
{
struct node *font; //分别指向队列的头和尾
struct node *rear;
int n; //队列长度
};
//创建一个空队列
void create(struct linkQueue *Q)
{
//创建一个头节点
struct node *head = new node;
head->next = NULL;
Q->font = head;
Q->rear = head;
Q->n = 0;
};
//入队数据num
void queueInsert(struct linkQueue *Q, int num)
{
struct node *p = new node;
p->data = num;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
Q->n++;
};
//出队并打印出队的数据
void queuePop(struct linkQueue *Q)
{
struct node *temp;
if(Q->font->next != NULL)
{
temp = Q->font->next;
Q->font->next = Q->font->next->next;
cout<<temp->data<<endl;
delete(temp);
if(Q->font->next == NULL)
Q->rear = Q->font;
Q->n--;
}
};
//打印
void print(struct linkQueue *Q)
{
cout<<"打印开始!"<<endl;
struct node *temp = Q->font;
if(temp == Q->rear)
cout<<"队列为空!"<<endl;
else
{本文
while(temp != Q->rear)
{
cout<<temp->next->data<<endl;
temp = temp->next;
}
}
cout<<"打印结束!"<<endl;
cout<<endl;
}
int main()
{
linkQueue Q;
create(&Q);
/********入队*************/
queueInsert(&Q, 1);
queueInsert(&Q, 2);
queueInsert(&Q, 3);
queueInsert(&Q, 4);
print(&Q);
/********出队*************/
queuePop(&Q);
print(&Q);
queuePop(&Q);
print(&Q);
queuePop(&Q);
print(&Q);
queuePop(&Q);
print(&Q);
return 0;
}