C Solution (0ms) - using two `realloc` based stacks


  • 0
    #define stack_new(s, type)     type *s; int s##Size
    #define stack_init(s)          s = NULL; s##Size = 0
    #define stack_push(s, type, x) s = realloc(s, ++s##Size * sizeof(type)); s[s##Size - 1] = x
    #define stack_pop(s, type)     s = realloc(s, --s##Size * sizeof(type))
    #define stack_top(s)           s[s##Size - 1]
    #define stack_empty(s)         (s##Size == 0)
    #define stack_size(s)          s##Size
    #define stack_delete(s)        free(s)
    
    typedef struct {
        stack_new(s1, int);
        stack_new(s2, int);
    } Queue;
    
    /* Create a queue */
    void queueCreate(Queue *queue, int maxSize) {
        stack_init(queue->s1);
        stack_init(queue->s2);
    }
    
    /* Push element x to the back of queue */
    void queuePush(Queue *queue, int element) {
        stack_push(queue->s1, int, element);
    }
    
    /* Get the front element */
    int queuePeek(Queue *queue) {
        int element;
        if (stack_empty(queue->s2)) {
            while (!stack_empty(queue->s1)) {
                element = stack_top(queue->s1);
                stack_pop(queue->s1, int);
                stack_push(queue->s2, int, element);
            }
        }
        return stack_top(queue->s2);
    }
    
    /* Removes the element from front of queue */
    void queuePop(Queue *queue) {
        queuePeek(queue);
        stack_pop(queue->s2, int);
    }
    
    /* Return whether the queue is empty */
    bool queueEmpty(Queue *queue) {
        return stack_empty(queue->s1) && stack_empty(queue->s2);
    }
    
    /* Destroy the queue */
    void queueDestroy(Queue *queue) {
        stack_delete(queue->s1);
        stack_delete(queue->s2);
    }
    

Log in to reply
 

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