这个的实现和前面的栈大同小异,就不多叙述了
// queue
//除了这种还有双端队列
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define INIT_SIZE 100
#define INCRESMENT 10
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType * queue_head;
ElemType * queue_rear;
int queue_size;
}Queue;
//初始化队列
Status
InitQueue(Queue * q)
{
q->queue_head = (ElemType *)malloc(INIT_SIZE * sizeof(ElemType));
if(q->queue_head == NULL)
return ERROR;
q->queue_rear = q->queue_head;
q->queue_size = INIT_SIZE;
return OK;
}
//销毁队列
Status
DestoryQueue(Queue * q)
{
if(q->queue_size > 0)
{
q->queue_size = 0;
}
free(q);
q = NULL;
return OK;
}
//清空队列
Status
ClearQueue(Queue *q)
{
while(q->queue_head != q->queue_rear)
q->queue_head ++;
q->queue_size = 0;
return OK;
}
//判断队列是否为空
Status
EmptyQueue(Queue q)
{
if(q.queue_head == q.queue_rear)
return OK;
else
return ERROR;
}
//返回队列的长度
int
LengthQueue(Queue q)
{
return q.queue_rear - q.queue_head;
}
//在队尾插入元素
//疑问:队尾指针在未插入前是正好指向还是什么样的指向,我先把它按栈一样的算吧
//对,就是一样的
Status
InsertQueue(Queue * q,ElemType e)
{
if( q->queue_rear - q->queue_head >= INIT_SIZE )
{
q->queue_head = (ElemType *)realloc
(q,(q->queue_size+INCRESMENT)*sizeof(ElemType));
q->queue_rear = q->queue_head;
q->queue_size += INCRESMENT;
}
*q->queue_rear = e;
q->queue_rear ++;
return OK;
}
//在队头删除元素
Status
DeleteQueue(Queue * q)
{
if(q->queue_head == q->queue_rear)
return ERROR;
q->queue_head ++;
q->queue_size --;
return OK;
}
//获取队列头的元素的值
Status
GetTop(Queue q,ElemType *e)
{
if(q.queue_head == q.queue_rear)
return ERROR;
else
*e = *(q.queue_head);
return OK;
}
//遍历队列
Status
TraverseQueue(Queue q,void(*visit)(ElemType *c))
{
ElemType* temp;
temp = q.queue_head;
while(temp != q.queue_rear)
{
visit(temp);
temp ++;
}
printf("\n");
return OK;
}
void
visit(ElemType *c)
{
printf("%d ", *c);
}
int main(int argc, char const *argv[])
{
Queue q;
int head,length;
InitQueue(&q);
InsertQueue(&q,1);
InsertQueue(&q,2);
InsertQueue(&q,3);
InsertQueue(&q,4);
printf("after insert:\n");
TraverseQueue(q,visit);
DeleteQueue(&q);
printf("after delete:\n");
TraverseQueue(q,visit);
GetTop(q,&head);
printf("\nqueue_head element is: %d ",head);
length = LengthQueue(q);
printf("\nqueue length is %d\n", length);
return 0;
}