队列也是表,使用队列时,插入在一端进行,而删除在另一端进行。
常用的操作:
/**是否为空队列**/ int isEmpty(Queue q) /**队列是否已满**/ int isFull(Queue q) /**实现循环队列,重置rear或者front**/ int circularQ(int index,Queue q) /*入列*/ void enQueue(Queue q,int item) /*出列*/ int deQueue(Queue q) /**取队列头元素**/ int front(Queue q)
Queue.c
#include <stdio.h> #include <stdlib.h> typedef struct QueueRec{ int front; int rear; int size;//队列元素个数 int capacity;//队列大小 int *Array; } lqueue,*Queue; int isEmpty(Queue q){ return q->size==0; } int isFull(Queue q){ return q->size==q->capacity; } Queue createQueue(int capacity){ Queue queue; queue = (Queue)malloc(sizeof(lqueue)); if(queue==NULL){ return NULL; } queue->Array = malloc(sizeof(int)*capacity); if(queue->Array == NULL ){ return NULL; } queue->capacity = capacity; queue->size = 0; queue->front = 0; queue->rear = -1; return queue; } void makEmpty(Queue q){ q->size = 0; q->rear = -1; q->front = 0; } void disPoseQueue(Queue q){ if(q!=NULL){ free(q); } } /**这个方法实现循环队列,当rear到达尾端(入列),或者front到达尾端(出列),它又回到开头**/ int circularQ(int index,Queue q){ if(++index > q->capacity){ return 0; } return index; } /*入列*/ void enQueue(Queue q,int item){ if(isFull(q)){ printf("Queue is Full\n"); } else { q->size ++; q->rear = circularQ(q->rear,q); q->Array[q->rear] = item; } } /*出列*/ int deQueue(Queue q){ int temp; if(isEmpty(q)){ printf("queue is Empty\n"); } else { q->size --; temp = q->Array[q->front]; q->front = circularQ(q->front,q); } return temp; } /**取队列头元素**/ int front(Queue q){ return q->Array[q->front]; } int main(void){ Queue q = createQueue(5); enQueue(q,1); enQueue(q,2); enQueue(q,3); enQueue(q,4); enQueue(q,5); enQueue(q,6); printf("%d\n",front(q)); printf("%d\n",deQueue(q)); printf("%d\n",deQueue(q)); enQueue(q,7); printf("%d\n",front(q)); disPoseQueue(q); return -1; }