前言:我之前有看過一些博主說,他們工作時要求做一個銀行排隊系統;
當然實現的方法各種各樣,今天介紹的是我們數據結構中的隊列queue,當然c++裏面有現成的可以用,甚至還有優先隊列,但瞭解原理也很重要啊!
依舊是我百度copy 的圖
當然除了線性隊列還有循環隊列,之前刷過的題裏面就涉及到了,依舊上圖
1、Queue CreatQueue( int MaxSize ):生成長度爲MaxSize的空隊列; 2、int IsFullQ( Queue Q, int MaxSize ):判斷隊列Q是否已滿;
3、void AddQ( Queue Q, ElementType item ) 將數據元素item插入隊列Q中;
4、int IsEmptyQ( Queue Q ): 判斷隊列Q是否爲空;
5、ElementType DeleteQ( Queue Q ):將隊頭數據元素從隊列中刪除並返回。
順序表
創建
同樣因爲是順序表,需要提前給出容量
typedef int Position;
struct QNode {
ElementType* Data; /* 存儲元素的數組 */
Position Front, Rear; /* 隊列的頭、尾指針 */
int MaxSize; /* 隊列最大容量 */
};
typedef struct QNode* Queue;
對首&隊尾
隊首和隊尾本身是不給值的
Queue CreateQueue(int MaxSize)
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType*)malloc(MaxSize * sizeof(ElementType));
Q->Front = Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
判斷隊列是否已滿
bool IsFull(Queue Q)
{
return ((Q->Rear + 1) % Q->MaxSize == Q->Front);
}
Front和rear 指針的移動 採用“加1取 餘”法,體 現了順序存 儲的“循環 使用”。
插入
插入肯定插在尾巴處嘛
你排隊也是先來後到 先進先出不是
bool AddQ(Queue Q, ElementType X)
{
if (IsFull(Q)) {
printf("隊列滿");
return false;
}
else {
Q->Rear = (Q->Rear + 1) % Q->MaxSize;
Q->Data[Q->Rear] = X;
return true;
}
}
判斷是否爲空
是否爲空只要看頭和尾是不是在一起
bool IsEmpty(Queue Q)
{
return (Q->Front == Q->Rear);
}
刪除
刪除你就頭指針往後挪一個唄
ElementType DeleteQ(Queue Q)
{
if (IsEmpty(Q)) {
printf("隊列空");
return ERROR;
}
else {
Q->Front = (Q->Front + 1) % Q->MaxSize;
return Q->Data[Q->Front];
}
}
鏈式表
創建
typedef struct Node* PtrToNode;
struct Node { /* 隊列中的結點 */
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
隊首&隊尾
此時你的容量是可以隨隊列的長度而更改的
struct QNode {
Position Front, Rear; /* 隊列的頭、尾指針 */
int MaxSize; /* 隊列最大容量 */
};
typedef struct QNode* Queue;
是否爲空
看隊首有沒有值唄
bool IsEmpty(Queue Q)
{
return (Q->Front == NULL);
}
刪除
先聲明定義指針和元素
刪除的話就要考慮兩種情況
只有一個元素和有多個元素
畢竟只有一個元素的時候隊首也沒有下一個結點給你☞了呀
ElementType DeleteQ(Queue Q)
{
Position FrontCell;
ElementType FrontElem;
if (IsEmpty(Q)) {
printf("隊列空");
return ERROR;
}
else {
FrontCell = Q->Front;
if (Q->Front == Q->Rear) /* 若隊列只有一個元素 */
Q->Front = Q->Rear = NULL; /* 刪除後隊列置爲空 */
else
Q->Front = Q->Front->Next;
FrontElem = FrontCell->Data;
free(FrontCell); /* 釋放被刪除結點空間 */
return FrontElem;
}
}
插入
和之前那些差不多啦
相信認真看到這
插入估計自己也會了!
只需要讓它指向隊尾所指的元素,再讓隊尾指向它就好了。
自己動手嘗試一下吧!