1.型別宣告
typedef struct CQueue {
struct SLnode* front;
struct SLnode* tail;
}CQueue;
typedef struct SLnode {
int date;
struct SLnode*next;
} SLnode;
2.創造節點
SLnode* BuySLnode() {
SLnode*node = (SLnode*)malloc(sizeof(SLnode));
if(node==NULL)
{
printf("Failed to open up capacity");
}
node->date = 0;
node->next = NULL;
return node;
}
3.型別宣告
CQueue* CQueueInit(int k)
{
CQueue*pq= (CQueue*)malloc(sizeof(CQueue));
if (pq == NULL)
{
printf("Failed to open up capacity");
}
SLnode*plist = BuySLnode();
SLnode*p = plist;
for (int i = 0; i < k; i++)
{
p->next = BuySLnode();
p = p->next;
}
p->next = plist;
p = NULL;//不用指標p了置空
pq->front = pq->tail = plist;
return pq;
}
構成一個回圈單鏈表,使CQueue->tail與CQueue->front指向回圈單鏈表的第一個節點,如果根據所需申請空間 判空與判滿無法判斷,所以需要多申請一個空間(不存放資料)
4. 判空
int CQueueIsEmpty(CQueue* pq)
{
return pq->front == pq->tail ? 1 : 0;
}
5.判滿
int CQueueIsFull(CQueue* pq)
{
SLnode*tailnext = pq->tail->next;
return tailnext == pq->front ? 1 : 0;
}
6.入隊
void CQueuePush(CQueue* pq, int value)
{
if (CQueueIsFull(pq))
{
return;
}
else
{
pq->tail->date = value;
pq->tail = pq->tail->next;;
}
}
7.出隊
void CQueuePop(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return ;
}
else
{
pq->front = pq->front->next;
}
}
8.獲取隊首的資料
int CQueueFront(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return -1;
}
return pq->front->date;
}
如果是空隊的話,回傳一個-1,
9.獲取隊尾的資料
int CQueueTail(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return -1;
}
SLnode*cur = pq->front;
while (cur->next != pq->tail)
{
cur = cur->next;
}
return cur->date;
}
獲取隊尾的資料,是需要找到tail前一個位置,而不是return tail->date
10.佇列的長度
int CQueueLength(CQueue*pq)
{
SLnode*cur = pq->front;
int size = 0;
while (cur != pq->tail)
{
cur = cur->next;
++size;
}
return size;
}
11.列印(為了更好的測驗各個介面)
void Print(CQueue*pq)
{
SLnode*cur = pq->front;
while (cur != pq->tail)
{
printf("%2d", cur->date);
cur = cur->next;
}
printf("\n");
}
11.置空
void CQueueDestory(CQueue* pq)
{
SLnode*cur = pq->front;
while (cur != pq->tail)
{
SLnode*next = cur->next;
free(cur);
cur = next;
}
free(cur);
pq->front = pq->tail = NULL;
free(pq);
pq = NULL;
}
注意這里傳的是一級指標,
12.測驗
test()
{
//測驗入隊
CQueue*cq = CQueueInit(5);
CQueuePush(cq, 2);
CQueuePush(cq, 3);
CQueuePush(cq, 4);
CQueuePush(cq, 5);
CQueuePush(cq, 6);
CQueuePush(cq, 7);
Print(cq);
//測驗出隊
CQueuePop(cq);
CQueuePop(cq);
Print(cq);
//獲取對頭的資料
printf("%2d\n", CQueueFront(cq));
//獲取對尾的資料
printf("%2d\n", CQueueTail(cq));
//佇列的長度,即有效資料的個數
printf("%2d\n", CQueueLength(cq));
//再次列印
Print(cq);
//釋放空間
CQueueDestory(cq);
cq = NULL;
}
由于傳的是一級指標 ,在CQueueDestory中,即使free(pq)了,但是在主函式Queue*cq會成為野指標,所以需要將cq=NULL.
13.測驗結果

單鏈表的模擬實作回圈佇列的基本操作就分享到這里了,感謝你的瀏覽,如果對你有幫助的話,可以給贊,順便點個關注,

下期將發布有關與雙向鏈表的基本操作的文章,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/319725.html
標籤:其他
上一篇:新世界的大門
下一篇:【C語言學習記錄】初識C語言
