本篇博客將實現隊列的鏈表結構,具體實現的操作有入隊、出隊、計算隊列長度、判斷隊列是否爲空、爲滿等。詳細工程代碼如下:
1.頭文件Queue_list.h
#pragma once
#ifndef QUEUE_LIST_H
#define QUEUE_LIST_H
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef int Element;
struct Node
{
Element data;
PtrToNode Next;
};
typedef struct
{
PtrToNode front, rear;
}Queue;
CreatQueue(Queue* Q);//創造空隊列,並且返回頭指針
int IsEmpty(Queue* Q);//判斷隊列是否爲空
void MakeEmpty(Queue* Q);//置空
int LengthOfQueue(Queue* Q);//計算隊列長度
void PrintQueue(Queue* Q);//打印隊列
void Enqueue(Queue* Q, Element data);//入隊列
void Dequeue(Queue* Q);//出隊列
#endif // !QUEUE_LIST_H
2.源文件Queue_list.c
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include"Queue_list.h"
CreatQueue(Queue* Q)//創造空隊列,並且返回頭指針
{
Q->front = Q->rear =(PtrToNode)malloc(sizeof(struct Node));
if (Q->front == NULL)
{
printf("out of space!!!");
exit(1);
}
Q->front->Next = NULL;
}
int IsEmpty(Queue* Q)//判斷隊列是否爲空
{
return Q->front == Q->rear;
}
void MakeEmpty(Queue* Q)//置空
{
if (Q == NULL)
{
printf("must use creatstack first!!");
exit(1);
}
else
{
while (!IsEmpty(Q))
Dequeue(Q);
}
}
int LengthOfQueue(Queue* Q)//計算隊列長度
{
int len = 0;
PtrToNode P = Q->front->Next;
while (P)
{
++len;
P = P->Next;
}
return len;
}
void PrintQueue(Queue* Q)//打印隊列
{
PtrToNode P = Q->front->Next;
if (IsEmpty(Q))
{
printf("Print Warning: the queue is empty !!!");
}
while (P)
{
printf("%d ", P->data);
P = P->Next;
}
printf("\n");
}
void Enqueue(Queue* Q, Element data)//入隊列
{
PtrToNode P = malloc(sizeof(struct Node));
P->data = data;
P->Next = NULL;
Q->rear->Next = P;
Q->rear = P;
}
void Dequeue(Queue* Q)//出隊列
{
PtrToNode P;
if (IsEmpty(Q))
{
printf("there is no element in the stack!!!");
exit(1);
}
P =Q->front->Next;
Q->front->Next =P->Next;
if (P == Q->rear)//如果只有一個元素,將尾指針移到頭指針。
{
Q->rear = Q->front;
}
free(P);
}
3.主程序main.c
#include"Queue_list.h"
int main()
{
Queue* Q =malloc(sizeof(Queue));//創建空隊列
CreatQueue(Q);
for (int i = 0; i < 10; i++)
{
Enqueue(Q, i);//入隊列
}
PrintQueue(Q);//打印隊列
printf("the length of the queue is: %d\n", LengthOfQueue(Q));//打印隊列長度
for (int i = 0; i < 3; i++)
{
Dequeue(Q);//出隊列
}
PrintQueue(Q);//打印隊列
printf("the length of the queue is: %d\n", LengthOfQueue(Q));//打印隊列長度
MakeEmpty(Q);
PrintQueue(Q);//打印隊列
printf("the length of the queue is: %d\n", LengthOfQueue(Q));//打印隊列長度
return 0;
}
4.運行結果