用链表来实现的队列为链式队列。用指针front和rear分别指向队头和队尾。同顺序队列一样,也是在front处出队,在rear处入队。
与顺序队列不同,链式队列的rear指针指向最后一个元素。
链式队列的C语言实现:(codeblocks完美运行)
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}pNode;
typedef struct Queue
{
pNode *front;
pNode *rear;
int size;
}queue;
queue *create()
{
queue *lq = (queue*)malloc(sizeof(queue));
lq->front = NULL;
lq->rear = NULL;
lq->size = 0;
}
int getsize(queue *lq)
{
return lq->size;
}
int IsEmpty(queue *lq)
{
if(lq->size == 0)
return 1;
return 0;
}
void insert(queue *lq,int val)
{
pNode *pn = (pNode*)malloc(sizeof(pNode));
pn->data = val;
pn->next = NULL;
if(IsEmpty(lq))
{
lq->front = pn;
lq->rear = pn;
}
else
{
lq->rear->next = pn;
lq->rear = pn;
}
lq->size++;
}
int getfront(queue *lq)
{
if(IsEmpty(lq))
{
printf("队列已为空");
return 0;
}
return lq->front->data;
}
int getrear(queue *lq)
{
if(IsEmpty(lq))
{
printf("队列已为空");
return 0;
}
return lq->rear->data;
}
pNode *del(queue *lq)
{
if(IsEmpty(lq))
{
printf("队列为空,删除错误!\n");
return NULL;
}
pNode *temp = lq->front;
lq->front = temp->next;
lq->size--;
return temp;
}
void clear(queue *lq)
{
lq->front = NULL;
lq->rear = NULL;
lq->size = 0;
printf("\n队列已清空!\n");
}
int main()
{
queue *lq = create();
srand((unsigned)time(0));
printf("入队30个元素\n");
int i;
for(i=0;i<30;i++)
insert(lq,rand()%300);
printf("队头元素为:%d\n",getfront(lq));
printf("队尾元素为:%d\n",getrear(lq));
printf("队列大小为:%d\n",getsize(lq));
printf("打印队列,同时也是出队操作!\n");
for(i=0;i<30;i++)
{
if(i%6 == 0)
printf("\n");
printf("%3d ",*((int *)del(lq)));
}
clear(lq);
return 0;
}