队列在我们生活中随处可见,在数据结构中的队列就是为了解决实际的排队问题。它同样关心的是数据的存取顺序,队列是一种先进先出(FIFO)的数据结构。
同样,这样的数据结构用单向链表实现相比于用数组实现更加有优势。
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Queue
{
struct Node *head;
struct Node *tail;
};
struct Queue* init()
{
struct Queue *qe=NULL;
qe = (struct Queue*)malloc(sizeof(struct Queue));
if(qe == NULL)
{
printf("create queue malloc error \n");
return NULL;
}
qe->head = (struct Node*)malloc(sizeof(struct Node));
if(qe->head == NULL)
{
free(qe);
printf("create node malloc error\n");
return NULL;
}
qe->head->next = NULL;
qe->head->data = 0;
qe->tail = qe->head;
return qe;
}
//入队
int in(struct Queue *qu, int data)
{
if(qu == NULL)
{
return -1;
}
struct Node *pnew = NULL;
pnew = (struct Node*)malloc(sizeof(struct Node));
if(pnew == NULL)
{
printf("in pnew malloc is fail\n");
return -1;
}
pnew->data = data;
pnew->next = NULL;
qu->tail->next = pnew;
qu->tail = qu->tail->next;
return 1;
}
int is_empty_linkqueue(struct Queue *qe)
{
if(qe == NULL)
{
return -1;
}
return ((qe->head == qe->tail) ? 1 : 0);
}
//出队
int out(struct Queue *qe)
{
int ret = 0;
if(qe == NULL)
{
return -1;
}
if(is_empty_linkqueue(qe) == 1)
{
return 0;
}
struct Node *pdel = NULL;
if(qe->head->next == NULL)
{
qe->tail = qe->head;
return 0;
}
pdel = qe->head->next;
qe->head->next = pdel->next;
ret = pdel->data;
free(pdel);
pdel = NULL;
return ret;
}
int main()
{
struct Queue *queue = NULL;
int var, i;
queue = init();
for (var = 0; var < 10; var++) {
in(queue, var);
}
for (i = 0; i < 10; i++) {
printf("queue%d:%d\n",i,out(queue));
}
}
以上是用单向链表的方式实现的队列,用数组实现队列的例子我在此就不给出了。由于用数组实现队列在出队是需要整体移动全队元素,运行效率较低,所以我推荐使用链表的方式实现队列。