在学习队列的时候我们需要理解到底队列是什么呢?队列与堆栈不一样的,队列的先进先出,堆栈是先入后出。
一、 在我们看代码之前我们需要了解两个结构体。如下:
1-1.这个是队列元素的结构体:
typedef struct node{
Item item;
struct node *next;
}Node;
1-2.下面是队列的结构体,包括了队列的当前数目以及对头指针和队尾指针:
typedef struct queue{
Node *font;
Node *rear;
int items;
}Queue;
二、下面是队列的实现代码:
2-1.队列初始化:
void InitQueue(Queue *pq)
{
pq->font = pq->rear = NULL;//把队列的头指针和尾指针初始化为空,避免野指针产生
pq->items = 0;//初始化队列当前数目
}
2-2.判断队列是否蛮:
bool QueueIsFull(const Queue *pq)
{
return pq->items == MAXQUEUE;
}
2-3判断队列是否为空:
bool QueueIsEmpty(const Queue *pq)
{
return pq->items == 0;
}
2-4。获取当前队列数目:
int QueueItemCount(const Queue *pq)
{
return pq->items;
}
2-5.copy元素到队列节点中:
int QueueItemCount(const Queue *pq)
{
return pq->items;
}
2-6.插入元素到队列中:
bool EnQueue(Item item,Queue *pq)
{
Node *pnew;
if(QueueIsFull(pq))//第一判断队列是否为满
return 0;
pnew = (Node*)malloc(sizeof(Node));//申请一个节点空间
if(pnew == NULL){
printf("malloc pnew fail.\n");
exit(1);
}
CopyToNode(item,pnew);//复制信息到节点中
pnew->next = NULL;//把节点中的next指针赋空
if(QueueIsEmpty(pq)){//判断队列是否为空,为空则把此节点插入到队列头
pq->font = pnew;
}
else
pq->rear->next = pnew;//不为空的话就插入到尾结点的下一个
pq->rear = pnew;//移动尾节点到新插入的节点处
pq->items ++;//队列数累加
printf("pq->items=%d\n",pq->items);
return 1;
}
2-7.一处一个队列元素:
bool DeQueue(Item *pitem,Queue *pq)
{
Node *pt;
if(QueueIsEmpty(pq))//判断队列是否为空
return 0;
pt = pq->font;//存储头结点元素地址到临时变量中,给后面释放此节点的空间使用
pq->font = pq->font->next;//移动头结点指针到后一位
free(pt);//释放节点
pq->items --;//队列元素减一
if(pq->items == 0)
pq->rear = NULL;
return 1;
}
三、测试队列函数:
int main(void)
{
Queue line;
Item temp;
char ch;
InitQueue(&line);
while((ch = getchar()) != 'q')
{
if((ch != 'a')&&(ch != 'd'))
continue;
if(ch == 'a'){
printf("scanf temp\n");
scanf("%d",&temp);
if(!QueueIsFull(&line)){
printf("will enter %d temp into line.\n",temp);
EnQueue(temp,&line);
}else{
printf("the queue is full.\n");
}
}else if(ch == 'd'){
if(QueueIsEmpty(&line)){
printf("will delete temp .\n");
DeQueue(NULL,&line);
}else{
printf("the queue is empty.\n");
}
}
}
}
以上的代码在linux上面编译并自己测试通过了的,大家可以放心使用,虽然简单,但是队列的思路就是这样。。。