这道题考察的是栈的使用,两个栈可以实现一个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);
*/