隊列也是一種特殊的線性表,其特點是先進先出,順序存儲結構的隊列存在數組溢出的情況,所以一般選擇鏈式存儲結構。
1.頭文件queue.h
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
}QueueNode,*QueuePtr;
typedef struct NodeFlag
{
QueuePtr front,rear;
}LinkQueue;
//創建隊列
bool CreateQueue(LinkQueue &Q);
//進隊列
bool InQueue(LinkQueue &Q,ElemType e);
//出隊列
bool OutQueue(LinkQueue &Q);
//打印隊列
bool print(LinkQueue Q);
2.queue.cpp
#include <iostream>
#include <malloc.h>
#include "queue.h"
bool CreateQueue(LinkQueue &Q)
{
QueuePtr q;
if(q=(QueuePtr)malloc(sizeof(QueueNode)))
{
q->data=NULL;
q->next=NULL;
Q.front=q;
Q.rear=q;
return true;
}
else
return false;
}
bool InQueue(LinkQueue &Q,ElemType e)
{
QueuePtr q;
if(q=(QueuePtr)malloc(sizeof(QueueNode)))
{
q->data=e;
q->next=NULL;
Q.rear->next=q;
Q.rear=q;
return true;
}
return false;
}
bool OutQueue(LinkQueue &Q)
{
QueuePtr q;
q=Q.front->next;
Q.front->next=q->next;
free(q);
return true;
}
bool print(LinkQueue Q)
{
QueuePtr q;
q=Q.front->next;
while(q)
{
printf("%d\n",q->data);
q=q->next;
}
printf("-------------分割線-----------------\n");
return true;
}
3.主函數main.cpp
#include <iostream>
#include "queue.h"
int main()
{
LinkQueue Q;
CreateQueue(Q);//創建隊列
for(int i=1;i<=10;i++)
InQueue(Q,i);
print(Q);
OutQueue(Q);
print(Q);
return 0;
}