以下为“使用链表实现顺序队列”的简单示例,由于使用数组实现队列时存在“假溢出”问题,建议使用链表方式实现顺序队列:
1. 用c语言实现的版本
#include<stdio.h>
#include<stdlib.h>
typedef int DataType; /* 假定队列元素的数据类型为整型 */
typedef struct node{
DataType data;
struct node *next;
}QueueNode;
typedef struct{
QueueNode *front; /*头指针*/
QueueNode *rear;
int count;
}LinkQueue;
/*初始化队列,将顺序队列置空*/
void Initial(LinkQueue *Q)
{
Q->front = Q->rear = NULL;
Q->count = 0;
}
/* 判断队列是否为空 */
int IsEmpty(LinkQueue *Q)
{
return Q->front == NULL && Q->rear == NULL;
}
/* 进入队列,添加尾结点 */
int Push(LinkQueue *Q, DataType x)
{
/*将元素x插入链队列尾部*/
QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));/*申请新结点*/
if (!p) //申请内存失败
{
return -1;
}
p->data = x;
p->next = NULL;
if (IsEmpty(Q)) /* 队列为空 */
{
Q->front = Q->rear = p;
}
else /* 队列非空 */
{
Q->rear->next = p; /*p链到原队尾结点后*/
Q->rear = p; /*队尾指针指向新的尾*/
}
++Q->count;
return 1;
}
/* 弹出队列,删除头节点 */
int Pop(LinkQueue *Q, DataType *x)
{
QueueNode *p;
if (IsEmpty(Q))
{
return -1;
}
p = Q->front; /*指向头结点*/
*x = p->data; /*保存头结点的数据*/
Q->front = p->next; /*将头结点从链上摘下*/
if (Q->rear == p)/*队列中只有一个结点,删去后队列变空,此时队头指针已为空*/
{
Q->rear = NULL;
}
free(p); /*释放被删队头结点*/
--Q->count;
return 1; /*返回原队头数据*/
}
/* 取队列顶元素*/
int Front(LinkQueue *Q, DataType* x)
{
if (IsEmpty(Q))
{
return -1;
}
*x = Q->front->data;
return 1;
}
/* 获取队列长度 */
DataType Length(LinkQueue *Q)
{
return Q->count;
}
void main()
{
LinkQueue s;
int select, res;
DataType value;
Initial(&s);/*初始化队列,将顺序队列置空*/
printf("(1)Input a queue data.\n");
printf("(2)Output a queue data.\n");
printf("(3)Get first queue data.\n");
printf("(4)Get queue length.\n");
printf("(5)Exit.\n");
printf("Please select your choice: ");
scanf("%d", &select);
do
{
switch (select)
{
case 1:
printf("Please input the digit(n is positive): ");
scanf("%d", &value);
res = Push(&s, value);;/* 进入队列 */
if (res != -1)
{
printf("[%d]已进入队列\n", value);
}
else
{
printf("队列已满\n");
}
break;
break;
case 2:
res = Pop(&s,&value); /* 弹出队列 */
if (res != -1)
{
printf("弹出值是: [%d]\n", value);
}
else
{
printf("队列为空.\n");
}
break;
case 3:
res = Front(&s, &value); /* 获取首元素 */
if (res != -1)
{
printf("首元素是: [%d]\n", value);
}
else
{
printf("未能获取首元素,队列为空\n");
}
break;
case 4:
value = Length(&s); /* 获取队列长度 */
printf("队列长度为:[%d]\n", value);
break;
default:
printf("Please input the right choice !\n");
break;
}
printf("\n(1)Input a queue data.\n");
printf("(2)Output a queue data.\n");
printf("(3)Get first queue data.\n");
printf("(4)Get queue length.\n");
printf("(5)Exit.\n");
printf("Please select your choice: ");
scanf("%d", &select);
} while (select != 5);
printf("\n");
}
运行结果如下图所示: