做網(wǎng)站可以用電腦當(dāng)服務(wù)器嗎/百度營銷
我們知道隊(duì)列的實(shí)現(xiàn)可以用單鏈表和數(shù)組,但是循環(huán)鏈表也可以使用這兩種方式。
首先我們來看看單鏈表:
首先使用單鏈表,我們需要考慮循環(huán)隊(duì)列的一些特點(diǎn)。

單鏈表實(shí)現(xiàn)循環(huán)隊(duì)列我們要考慮幾個(gè)核心問題:
首先我們要區(qū)別 解決 空 和 滿 的問題。多加一個(gè)空間,或者加一個(gè)size變量來記錄。
當(dāng)front==rail時(shí),為空。
當(dāng)rail->next == front時(shí)為滿
其次,我們需要解決如何 能取出隊(duì)尾的數(shù)據(jù)。對于單鏈表,因?yàn)槲覀價(jià)ail指向隊(duì)尾的后一個(gè),所以不好取出隊(duì)尾數(shù)據(jù)
數(shù)組來實(shí)現(xiàn) 循環(huán)鏈表:
同樣當(dāng)front==rail時(shí),為空
當(dāng) front == (rail+1)%(k+1)時(shí)為滿
數(shù)組解決循環(huán)鏈表,我們要考慮到:當(dāng)不斷出隊(duì)和入隊(duì)時(shí)如何循環(huán)起來?
可以使用if語句來判斷,也可以給讓rail超出數(shù)組大小后,直接回到數(shù)組開頭。

當(dāng)rail在第一個(gè)位置時(shí),如何找到隊(duì)尾元素呢?
我們可以使用if,也可以(rail+k)%(k+1)來取到前一個(gè)元素。
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>typedef struct {int* a;int front;int rail;int k;
}MyQueue;MyQueue* MyQueueCreat(int k)
{MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));obj->a = (int*)malloc(sizeof(int) * (k + 1));obj->front = obj->rail = 0;obj->k = k;
}
bool isMyQueueEmtp(MyQueue* obj)
{assert(obj);if (obj->front == obj->rail)return true;return false;
}
bool isMyQueueFull(MyQueue* obj)
{assert(obj);return (obj->rail + 1) % (obj->k + 1) == obj->front;
}
bool MyQueueEn(MyQueue* obj, int value)
{assert(obj);if (isMyQueueFull(obj))return -1;obj->a[obj->rail++] = value;obj->rail %= obj->k + 1;
}
bool MyQueueOut(MyQueue* obj)
{assert(obj);obj->front++;obj->front %= obj->k + 1;}int MyQueueFront(MyQueue* obj)
{assert(obj);return obj->a[obj->front];
}
int MyQueueRail(MyQueue* obj)
{asert(obj);if (isMyQueueEmtp(obj))return - 1;return obj->a[obj->rail + obj->k % obj->k + 1];
}void MyQueueFree(MyQueue* obj)
{assert(obj);free(obj->a);free(obj);
}
好的,今天的復(fù)習(xí)就到這里