美文网首页
剑指offer 9 双栈实现队列

剑指offer 9 双栈实现队列

作者: 再凌 | 来源:发表于2020-04-28 22:04 被阅读0次

    这道题思路很清晰明了

    typedef struct {
        struct stack{
            int data[10000];
            int top;
        }stack[2];
    } CQueue;
    
    
    CQueue* cQueueCreate() {
        CQueue *result = (CQueue*) malloc(sizeof(CQueue));
        result->stack[0].top = -1;
        result->stack[1].top = -1;
        return result;
    }
    
    void cQueueAppendTail(CQueue* obj, int value) {
        obj->stack[0].top += 1;
        obj->stack[0].data[obj->stack[0].top] = value;
    }
    
    int cQueueDeleteHead(CQueue* obj) {
        if(obj->stack[0].top == -1) return -1;
        while(obj->stack[0].top>0)
        {
            obj->stack[1].top += 1;
            obj->stack[1].data[obj->stack[1].top] = obj->stack[0].data[obj->stack[0].top--];
        }
        int temp = obj->stack[0].data[obj->stack[0].top--];
        while(obj->stack[1].top>-1)
        {
            obj->stack[0].top += 1;
            obj->stack[0].data[obj->stack[0].top] = obj->stack[1].data[obj->stack[1].top--];
        }
        return temp;
    }
    
    void cQueueFree(CQueue* obj) {
        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);
    */
    

    相关文章

      网友评论

          本文标题:剑指offer 9 双栈实现队列

          本文链接:https://www.haomeiwen.com/subject/xzciwhtx.html