初始化
typedef int elemtype;
typedef struct Node {
elemtype data;//数据域
struct Node*next;
}Qnode,*QueuePtr;
typedef struct{
QueuePtr front ,rear;
}LinkQueue;
int Init_LinkQueue(LinkQueue* L) {
Qnode* S;
S = (Qnode*)malloc(sizeof(Node));
if (!S)
{
printf("初始化失败\n");
return 0;
}
S->next = NULL;
L->front = S;
L->rear = S;
return 0;
}
进队列
int EnQueue(LinkQueue* L, elemtype e)
{
Qnode* S;
S = (Qnode*)malloc(sizeof(Node));
if (!S)
{
printf("插入失败!\n");
return 0;
}
S->data = e;
S->next = NULL;
L->rear->next = S;
L->rear = S; //让新加入的节点S设置为新的队尾节点
return 0;
}
出队列
int DeQueue(LinkQueue* L, elemtype* e)
{
Qnode* S;
S = (Qnode*)malloc(sizeof(Node));
if (!S)
{
printf("当前队列为空,无法删除元素!\n");
return 0;
}
S = L->front->next; //将欲删除的队头节点赋值给S
*e = S->data;
L->front->next = S->next;
if (S ==L->rear)
{
L->rear = L->front;//将要删除节点的下一个节点赋值给头节点的后继
}
free(S);
return 0;
}
计算队列长度
int Length_LinkQueue(LinkQueue* L) {
Qnode* S;
int count = 0;
S = L->front;
while (L->front != L->rear)
{
count++;
L->front = L->front->next;
}
L->front = S;
return count;
}
展示队列元素
void Show_LinkQueue(LinkQueue* L) //打印队列函数
{
if (L->front == L->rear)
{
printf("队列为空!\n");
return;
}
Qnode* S;
S = L->front; //将头指针暂存在S
L->front = L->front->next; //先将头指针指向头结点的后继节点,即第一个节点
printf("当前队列元素为:");
while (L->front) //当没有到尾节点,就一直循环
{
printf("%d ", L->front->data);
L->front = L->front->next;
}
printf("\n");
L->front = S; //将头指针回到原位置
}
运行
int main()
{
LinkQueue L;
elemtype m;
Init_LinkQueue(&L);
Show_LinkQueue(&L);
printf("队列的长度为%d\n", Length_LinkQueue(&L));
EnQueue(&L, 5);
EnQueue(&L, 3);
EnQueue(&L, 32);
EnQueue(&L, 65);
Show_LinkQueue(&L);
printf("队列的长度为%d\n", Length_LinkQueue(&L));
DeQueue(&L, &m);
printf("被删除元素为:%d\n", m);
DeQueue(&L, &m);
printf("被删除元素为:%d\n", m);
Show_LinkQueue(&L);
printf("队列的长度为%d\n", Length_LinkQueue(&L));
system("pause");
return 0;
}