Anyone know how to do this in C?


  • 0
    M

    Hi folks, I am using C to do this task and get a runtime error with input 'empty'. The thing is, I don't quite understand what the code supposed to be in C.. My wrong code is as follows. Hope someone could enlighten me a little bit.

    int stone = 0;
    int sttwo = 0;
    
    typedef struct {
        int *stack1;
        int *stack2;
    } Queue;
    
    /* Create a queue */
    void queueCreate(Queue *queue, int maxSize) {
        queue = (Queue *)malloc(sizeof(Queue *));
        int *stack1 = (int *)malloc(sizeof(int)*maxSize);
        int *stack2 = (int *)malloc(sizeof(int)*maxSize);
        
        queue->stack1 = stack1;
        queue->stack2 = stack2;
    }
    
    /* Push element x to the back of queue */
    void queuePush(Queue *queue, int element) {
        queue->stack1[stone++] = element;
    }
    
    /* Removes the element from front of queue */
    void queuePop(Queue *queue) {
        if (sttwo > 0)
            sttwo--;
        else {
            while (stone > 0)
                queue->stack2[sttwo++] = queue->stack1[--stone];
            sttwo--;
        }
    }
    
    /* Get the front element */
    int queuePeek(Queue *queue) {
        if (sttwo > 0)
            return queue->stack2[sttwo-1];
        else {
            while (stone > 0)
                queue->stack2[sttwo++] = queue->stack1[--stone];
            return queue->stack2[sttwo-1];
        }
    }
    
    /* Return whether the queue is empty */
    bool queueEmpty(Queue *queue) {
        if (stone == 0 && sttwo == 0)
            return true;
        else
            return false;
    }
    
    /* Destroy the queue */
    void queueDestroy(Queue *queue) {
        free(queue->stack1);
        free(queue->stack2);
        free(queue);
    }
    
    /*
    //Queue *queue;
    //int maxSize = 100;
    //queueCreate(queue, maxSize);
    
    void push(int element) {
        queuePush(queue, element);
    }
    void pop(void) {
        queuePop(queue);
    }
    
    int peek(void) {
        return queuePeek(queue);
    }
    
    bool empty(Queue *queue) {
        return queueEmpty(queue);
    }*/

  • 0
    N

    I meet the same dilemma with you...Maybe the compiler problem?


  • 3
    J

    there are two issues in your code:

    1. In queueCreate(), queue is the local pointer, you have no way to return it to the caller. So we assume the caller has already allocated the memory for queue, dont need to allocate memory for queue in queueCreate().

    don't do "free(queue)" in queueDestroy(), queue is the allocated from outside, it may not in the heap, it may be the local var or static var in the caller. so please do not free it.


  • 0
    M

    good points!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.