Leetcode 剑指 Offer 09 用两个栈实现队列

39 篇文章 0 订阅
34 篇文章 0 订阅

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值