当前位置 博文首页 > L_add的博客:用栈实现队列

    L_add的博客:用栈实现队列

    作者:[db:作者] 时间:2021-08-27 10:03

    用栈实现队列

    题目描述(题目来源:力扣)
    在这里插入图片描述
    思路:
    在这里插入图片描述

    typedef struct {
        Stack pushST;
        Stack popST;
    } MyQueue;
    
    /** Initialize your data structure here. */
    
    MyQueue* myQueueCreate() {
        MyQueue*q =(MyQueue*) malloc(sizeof(MyQueue));
        StackInit(&q->popST);
        StackInit(&q->pushST);
        return q;
    }
    
    /** Push element x to the back of queue. */
    void myQueuePush(MyQueue* obj, int x) {
        StackPush(&obj->pushST,x);
    
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int myQueuePop(MyQueue* obj) {
      /*  if(!StackEmpty(&obj->popST))
        {
            while(!StackEmpty(&obj->pushST));
             {
                  StackPush(&obj->popST,StackTop(&obj->pushST));
                  StackPop(&obj->pushST);
             }  
        }*/
        int top = myQueuePeek(&obj->popST);
        StackPop(&obj->popST);
        return top;
    }
    
    /** Get the front element. */
    int myQueuePeek(MyQueue* obj) {
        if(StackEmpty(&obj->popST))
        {
            while(!StackEmpty(&obj->pushST));
             {
                  StackPush(&obj->popST,StackTop(&obj->pushST));
                  StackPop(&obj->pushST);
             }  
        }
        return StackPop(&obj->popST);
    }
    
    /** Returns whether the queue is empty. */
    bool myQueueEmpty(MyQueue* obj) {
        StackEmpty(&obj->pushST)&&StackEmpty(&obj->popST);
    }
    
    void myQueueFree(MyQueue* obj) {
        StackDestory(&obj->pushST);
        StackDestory(&obj->popST);
        free(obj);
    }
    
    cs
    下一篇:没有了