数据结构——基本数据结构之队列

来源:互联网 发布:小米笔记本12.5编程 编辑:程序博客网 时间:2024/06/07 21:02
 

循环队列
用一组抵制连续的存储单元依次存放从队头到队尾的元素
另外两个指针front和rear分别指示队列头元素和尾元素的位置

queue.h

#ifndef _QUEUE_H
#define _QUEUE_H

#define MaxQSize 100
typedef
int ElemType;

typedef
struct SqQueue...{
ElemType
*base;
int front;
int rear;
}
Queue;

int InitQueue(Queue**q);
int DestroyQueue(Queue**q);
int ClearQueue(Queue**q);
int QueueEmpty(Queue*q);
int QueueLength(Queue*q);
int GetHead(Queue*q, ElemType*e);
int EnQueue(Queue**q, ElemType e);
int DeQueue(Queue**q, ElemType*e);

#endif


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

int InitQueue(Queue**q)
...{
(
*q)->base= (ElemType*)malloc(MaxQSize* sizeof(ElemType));
if(!(*q)->base)
return 0;
(
*q)->front= 0;
(
*q)->rear= 0;

return 1;
}


int QueueEmpty(Queue*q)
...{
if(q->rear== q->front)
return 1;
else
return 0;
}


int QueueLength(Queue*q)
...{
return (q->rear- q->front+ MaxQSize)% MaxQSize;
}


int EnQueue(Queue**q, ElemType e)
...{
if(((*q)->rear+ 1)% MaxQSize == (*q)->front)
return 0;
(
*q)->base[(*q)->rear]= e;
(
*q)->rear= ((*q)->rear+ 1)% MaxQSize;

return 1;
}


int DeQueue(Queue**q, ElemType*e)
...{
if((*q)->rear== (*q)->front)
return 0;
*e = (*q)->base[(*q)->front];
(
*q)->front= ((*q)->front+ 1)% MaxQSize;

return 1;
}

QueueMain.c
#include<stdio.h>
#include
"queue.h"

int main(int argc,char **argv)
...{
ElemType e;
Queue
*q;

q
= (Queue *)malloc(sizeof(Queue));
InitQueue(
&q);
while((e = getchar()) != '#')
...{
EnQueue(
&q, e);
}

while(!QueueEmpty(q))
...{
DeQueue(
&q,&e);
printf(
"%c", e);
}


return 0;
}