顺序循环队列
队头插入元素,队尾删除元素
本来应该判空和判断是否存满的条件都是:队头 = 队尾,但这样就没办法区分了,所以,就牺牲一个空间(比如长度为10,但只能存9个),这样判断是否存满就变成了队头 = (队尾+1)% 队列长度。
顺序循环队列判空条件:队头 = 队尾
顺序循环队列判断是否存满条件:队头 = (队尾+1)% 队列长度
1.定义结构体
2.创建
SeqQueue *CreateSeqQueue(int MaxLen)
{SeqQueue *pTmpQueue = NULL;pTmpQueue = malloc(sizeof(SeqQueue));if (NULL == pTmpQueue){return NULL;}pTmpQueue->Head = pTmpQueue->Tail = 0;pTmpQueue->Len = MaxLen;pTmpQueue->pData = malloc(sizeof(DataType) * MaxLen);if (NULL == pTmpQueue->pData){return NULL;}return pTmpQueue;
}
3.判空
int IsEmptySeqQueue(SeqQueue *pTmpQueue)
{return pTmpQueue->Head == pTmpQueue->Tail ? 1 : 0;
}
4.判断是否存满
int IsFullSeqQueue(SeqQueue *pTmpQueue)
{return (pTmpQueue->Tail + 1) % pTmpQueue->Len == pTmpQueue->Head ? 1 : 0;
}
5.入队
int EnterSeqQueue(SeqQueue *pTmpQueue, DataType TmpData)
{if (IsFullSeqQueue(pTmpQueue)){return -1;}pTmpQueue->pData[pTmpQueue->Tail] = TmpData;pTmpQueue->Tail = (pTmpQueue->Tail + 1) % pTmpQueue->Len;return 0;
}
6.出队
DataType QuitSeqQueue(SeqQueue *pTmpQueue)
{DataType TmpData;TmpData = pTmpQueue->pData[pTmpQueue->Head];pTmpQueue->Head = (pTmpQueue->Head + 1) % pTmpQueue->Len;return TmpData;
}
7.销毁
int DestroySeqQueue(SeqQueue **ppTmpQueue)
{free((*ppTmpQueue)->pData);free(*ppTmpQueue);*ppTmpQueue = NULL;return 0;
}