1.队列的定义
队列是一种先进先出的线性表,它只允许在表的一端进行插入,而在另一端删除元素。这和我们日常生活中的排队是一致的,最早进入队列的元素最早离开。
2.链队列结构
链队列,是队列的一种,只不过运用链表的知识对队列进行再设计。
3.基本操作
3.1结构体
typedef struct linkNode
{
int data;
struct linkNode* next;
}*linkNodeptr;typedef struct linkQueue
{
linkNodeptr front;
linkNodeptr rear;
}*linkQueueptr;
3.2初始化
linkQueueptr initQueue()
{
linkQueueptr resultptr=(linkQueueptr)malloc(sizeof(struct linkQueue));
linkNodeptr headerptr=(linkNodeptr)malloc(sizeof(struct linkNode));
headerptr->data=-1;
headerptr->next=NULL;
resultptr->front=headerptr;
resultptr->rear=headerptr;
return resultptr;
}
3.3进队
void enqueue(linkQueueptr pQueueptr,int pelement)
{
linkNodeptr tempNodeptr=(linkNodeptr)malloc(sizeof(struct linkNode));
tempNodeptr->data=pelement;
tempNodeptr->next=NULL;
pQueueptr->rear->next=tempNodeptr;
pQueueptr->rear=tempNodeptr;
}
3.4出队
int dequeue(linkQueueptr pQueueptr)
{
int resultValue;
linkNodeptr tempNodeptr;
if(pQueueptr->front==pQueueptr->rear)
{
printf("队列为空! 无法删除!\r\n");
return -1;
}
tempNodeptr=pQueueptr->front->next;
resultValue=tempNodeptr->data;
pQueueptr->front->next=pQueueptr->front->next->next;
if(pQueueptr->rear==tempNodeptr)
{
pQueueptr->rear=pQueueptr->front;
}
free(tempNodeptr);
return resultValue;
}
3.5遍历
void printQueue(linkQueueptr pQueueptr)
{
linkNodeptr tempptr=pQueueptr->front->next;
while(tempptr)
{
printf("%d ",tempptr->data);
tempptr=tempptr->next;
}
printf("\r\n");
}
4.运行结果
10 100 1000 10000
dequeue gets 10!
dequeue gets 100!
dequeue gets 1000!
dequeue gets 10000!
队列为空! 无法删除!
dequeue gets -1!
5.总结
通过此章节的学习,可以尝试排队呼叫系统的编程