您的位置:首页 > 其它

队列及其应用

2016-10-18 06:05 183 查看

1.队列的基础

队列是插入只能在一端(后端),删除只能在另一端(前端)的线性表,是先进先出模型。

1. 入队:在表的末端插入;

2. 出队:在表的开头删除元素;

2.队列的应用

汽车加油站

模拟打印机缓冲区

CPU分时系统、计算机网络

打印杨辉三角

3.队列的数组实现

1. fatal.h

#include <stdio.h>
#include <stdlib.h>

#define Error( Str )   FatalError( Str )
#define FatalError( Str )   fprintf( stderr, "%s\n", Str ),system("puase"),getchar(),exit( 1 )


2.queue.h

#include <stdio.h>
typedef int ElementType;

#ifndef _Queue_h
struct QueueRecord;
typedef struct QueueRecord *Queue;

int IsEmpty(Queue Q);
int IsFull(Queue Q);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
void Enqueue(ElementType X, Queue Q);
ElementType Front(Queue Q);
void Dequeue(Queue Q);
ElementType FrontAndDequeue(Queue Q);

#endif


  

3.queue.c

#include "queue.h"
#include "fatal.h"
#include <stdlib.h>

#define MinQueueSize (5)

struct QueueRecord
{
int Capacity;
int Front;
int Rear;
int Size;
ElementType *Array;
};

int IsEmpty(Queue Q)
{
return Q->Size == 0;
}

Queue CreateQueue(int MaxElements)
{
Queue Q;
if (MaxElements < MinQueueSize)
{
Error("Queue is too small\n");
}

Q = malloc(sizeof(struct QueueRecord));
if (Q==NULL)
{
FatalError("out of space!!!");
}

Q->Array = malloc(sizeof(ElementType)*MaxElements);
if (Q->Array == NULL)
{
FatalError("out of space!!!");
}

Q->Capacity = MaxElements;
MakeEmpty(Q);
return Q;
}

int IsFull(Queue Q)
{
return Q->Size == Q->Capacity;
}

void MakeEmpty(Queue Q)
{
Q->Size = 0;
Q->Front = 1;
Q->Rear = 0;
}

ElementType Front(Queue Q)
{
if (!IsEmpty(Q))
{
return Q->Array[Q->Front];
}

Error("Empty Queue\n");
return 0;
}
static int Succ(int Value, Queue Q)
{
if (++Value==Q->Capacity)
{
Value = 0;
}
return Value;
}
void Enqueue(ElementType X, Queue Q)
{
if (IsFull(Q))
{
Error("Full Queue\n");
}
else
{
Q->Size++;
Q->Rear = Succ(Q->Rear, Q);
Q->Array[Q->Rear] = X;
}
}

void Dequeue(Queue Q)
{
if (!IsEmpty(Q))
{
Q->Size--;
Q->Front = Succ(Q->Front, Q);
}
else
{
Error("Empty Queue\n");
}
}

ElementType FrontAndDequeue(Queue Q)
{
ElementType X = 0;
if (IsEmpty(Q))
{
Error("Empty Queue\n");
}
else
{
Q->Size--;
X = Q->Array[Q->Front];
Q->Front = Succ(Q->Front, Q);
}
return X;
}

void DisposeQueue(Queue Q)
{
if (Q!=NULL)
{
free(Q->Array);
free(Q);
Q = NULL;
}
}


  

4.testqueue.c

#include "queue.h"
#include "fatal.h"
#include <stdio.h>
#include <stdlib.h>

void main()
{
Queue Q;
Q = CreateQueue(10);
for (int i = 0; i < 10; i++)
{
Enqueue(i, Q);
}

for (int i = 0; i < 10; i++)
{
ElementType data = Front(Q);
printf("%d\t", data);
Dequeue(Q);
}
printf("\n\n");

for (int i = 0; i < 10; i++)
Enqueue(i, Q);

for (int i = 0; i < 10; i++)
{
ElementType data = FrontAndDequeue(Q);
printf("%d\t", data);
}
printf("\n\n");
DisposeQueue(Q);

system("pause");
}


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