您的位置:首页 > 其它

队列 —— 链队列

2017-02-09 21:54 62 查看

队列



代码

/*
function:queue
created by : xilong
date: 2017.2.9
*/

#include "iostream"
using namespace std;

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Elemtype;
typedef int Status;
typedef struct QNode
{
Elemtype data;
struct QNode* next;
} QNode, *QueuePrt;

typedef struct
{
QueuePrt front, rear;
} LinkQueue;

/*
initialize the queue
*/
Status Init_Queue(LinkQueue *q)
{
q->front = q->rear = (QueuePrt)malloc(sizeof(QNode));
if (!q->front)
exit(0);
q->front->next = NULL;
return OK;
}

/*
Insert an element into the queue, an element can only be inserted into the end of the queue
*/
Status Inster_Queue(LinkQueue *q, Elemtype e)
{
QueuePrt p;
p = (QueuePrt)malloc(sizeof(QNode));
if (p == NULL)
exit(0);
p->data = e;
p->next = NULL;
q->rear->next = p;
q->rear = p;
return OK;
}

/*
Delete an element in the queue, an element which is in the front can only be deleted
*/
Status Delete_Queue(LinkQueue *q, Elemtype *e)
{
QueuePrt p;
if (q->front == q->rear)
{
cout << "空队!" << endl;
return FALSE;
}
p = q->front->next;
q->front->next = p->next;
if (q->rear == p)
{
q->rear = q->front;
}
*e = p->data;
free(p);
return TRUE;
}

/*
length of the queue
*/
int Length_Queue(LinkQueue *q)
{
QueuePrt p;
int len = 0;
p = q->front->next;
if (q->front == q->rear)
cout << "空队!" << endl;
while (p)
{
len++;
p = p->next;
}
return len;
}

void main()
{
LinkQueue q;
Elemtype e;
int i, len;
Init_Queue(&q);
Inster_Queue(&q, 1);
Inster_Queue(&q, 2);
Inster_Queue(&q, 3);
Inster_Queue(&q, 4);
Inster_Queue(&q, 5);
Inster_Queue(&q, 6);
Inster_Queue(&q, 7);
Inster_Queue(&q, 8);
len = Length_Queue(&q);
cout << "队列的长度为:";
cout << len << endl;
cout << "出对列的顺序为:";
for (i = 0; i < len; i++)
{
Delete_Queue(&q, &e);
cout << e << " ";
}
cout << endl;
system("pause");
}


截图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列 链队列