这道题考察的是栈的使用,两个栈可以实现一个FIFO
具体解题方法参考剑指offer 09
P.S. free可以把malloc分配的内存排空,在本题实现过程中需要先把CQueue中的stakebottom1, stakebottom2分配的内存先排空再排空CQueue.
内存和时间消耗以及源代码如下:

typedef struct {
int* stakebottom1;
int stakelength1;
int* stakebottom2;
int stakelength2;
} CQueue;
CQueue* cQueueCreate() {
CQueue* obj;
obj = (CQueue*) malloc (sizeof(CQueue));
obj->stakelength1 = 0;
obj->stakelength2 = 0;
obj->stakebottom1 = (int*) malloc (10000*sizeof(int));
obj->stakebottom2 = (int*) malloc (10000*sizeof(int));
return obj;
}
void cQueueAppendTail(CQueue* obj, int value) {
if (value != NULL)
{
obj->stakebottom1[obj->stakelength1] = value;
(obj->stakelength1)++;
}
}
int cQueueDeleteHead(CQueue* obj) {
if (obj->stakelength2 == 0)
{
while (obj->stakelength1 > 0)
{
(obj->stakelength1)--;
obj->stakebottom2[obj->stakelength2] =
obj->stakebottom1[obj->stakelength1];
obj->stakebottom1[obj->stakelength1] = NULL;
(obj->stakelength2)++;
}
}
if (obj->stakelength2 == 0)
{
return -1;
}
else
{
(obj->stakelength2)--;
int value = obj->stakebottom2[obj->stakelength2];
obj->stakebottom2[obj->stakelength2] = NULL;
return value;
}
}
void cQueueFree(CQueue* obj) {
free(obj->stakebottom1);
free(obj->stakebottom2);
free(obj);
}
/**
* Your CQueue struct will be instantiated and called as such:
* CQueue* obj = cQueueCreate();
* cQueueAppendTail(obj, value);
* int param_2 = cQueueDeleteHead(obj);
* cQueueFree(obj);
*/
本文介绍如何使用两个栈实现一个FIFO队列的数据结构。通过将元素压入第一个栈,然后在需要取出元素时,将第一个栈的元素依次弹出并压入第二个栈,从而实现队列的先进先出特性。文章详细解释了CQueue结构的创建、元素的添加和删除操作,并提供了C语言的实现代码。

258

被折叠的 条评论
为什么被折叠?



