分类: IT业界
2011-06-09 15:16:11
1、 数据结构
#define MAXQUEUE 100
struct SqQueue
{
int *base;
int front;
int rear;
};
2、构造一个空队列
void CreateQueue(struct SqQueue &Q)
{
Q.base = (int *)malloc(MAXQUEUE * sizeof(int));
if (Q.base == NULL)
{
exit(0);
}
Q.front = Q.rear = 0;
}
3、销毁队列
void DestroyQueue(struct SqQueue &Q)
{
if (Q.base != NULL)
{
free(Q.base);
Q.base = NULL;
Q.front = Q.rear = 0;
}
}
4、清空队列
void ClearQueue(struct SqQueue &Q)
{
Q.front = Q.rear = 0;
}
5、判断队列是否为空
bool EmptyQueue(struct SqQueue Q)
{
if (Q.front == Q.rear)
{
return true;
}
else
{
return false;
}
}
6、求队列长度
int LengthQueue(struct SqQueue Q)
{
int length = 0;
length = (Q.rear - Q.front + MAXQUEUE) % MAXQUEUE;
return length;
}
7、队列不空,则返回队头
void GetQueueHead(struct SqQueue Q, int &value)
{
if (!EmptyQueue(Q))
{
value = Q.base[Q.front];
}
}
8、队列不空,则删除队头
void DelQueueHead(struct SqQueue &Q, int &value)
{
if (!EmptyQueue(Q))
{
value = Q.base[Q.front];
Q.front = (Q.front+1)%MAXQUEUE;
}
}
9、插入元素到队列
void InsertQueue(struct SqQueue &Q, int value)
{
if ((Q.rear + 1) % MAXQUEUE == Q.front)
{
printf("队列已满\n");
return;
}
Q.base[Q.rear] = value;
Q.rear = (Q.rear + 1) % MAXQUEUE;
}
10、遍历队列元素
void TraverseQueue(struct SqQueue Q)
{
if (!EmptyQueue(Q))
{
int i = Q.front;
while (i != Q.rear)
{
printf("%d ", Q.base[i]);
i = (i+1) % MAXQUEUE;
}
printf("\n");
}
}