My solution use c program language


  • 0
    M
    typedef struct {
    int queue1[65535];
    int queue2[65535];
    int front1;
    int tail1;
    int total;
    int front2;
    int tail2;
    } Stack;
    
    /* Create a stack */
    void stackCreate(Stack *stack, int maxSize) {
    stack->total = maxSize;
    stack->front1 = 0;
    stack->tail1 = 0;
    stack->front2 = 0;
    stack->tail2 = 0;
    }
    
    /* Push element x onto stack */
    void stackPush(Stack *stack, int element) {
    if (stack->front1 - stack->tail1 == 0){
        if ((stack->tail2 + 1) % stack->total == stack->front2)
            return;
        stack->queue2[stack->tail2] = element;
        stack->tail2 = (stack->tail2 + 1) % stack->total;
        return ;
    }
    else{
        if ((stack->tail1 + 1) % stack->total == stack->front1)
            return;
        stack->queue1[stack->tail1] = element;
        stack->tail1 = (stack->tail1 + 1) % stack->total;
     }
    }
    
    /* Removes the element on top of the stack */ 
    void stackPop(Stack *stack) {
    if (stack->front1 - stack->tail1 == 0){
        while ((stack->front2+1) % stack->total != stack->tail2){
            stack->queue1[stack->tail1] = stack->queue2[stack->front2];
            stack->tail1 = (stack->tail1 + 1) % stack->total;
            stack->front2 = (stack->front2 + 1) % stack->total;
        }
        int m = stack->queue2[stack->front2];
        stack->front2 = (stack->front2 + 1) % stack->total;
        return m;
    }
    else{
        while ((stack->front1 + 1) % stack->total != stack->tail1){
            stack->queue2[stack->tail2] = stack->queue1[stack->front1];
            stack->tail2 = (stack->tail2 + 1) % stack->total;
            stack->front1 = (stack->front1 + 1) % stack->total;
        }
        int m = stack->queue1[stack->front1];
        stack->front1 = (stack->front1 + 1) % stack->total;
        return m;
    }
    }
    
    /* Get the top element */
    int stackTop(Stack *stack) {
    if (stack->front1 - stack->tail1 == 0){
        int p = (stack->tail2 - 1 + stack->total) % stack->total;
        return stack->queue2[p];
    }
    else{
        int p = (stack->tail1 - 1 + stack->total) % stack->total;
        return stack->queue2[p];
    }
    }
    
    /* Return whether the stack is empty */
    bool stackEmpty(Stack *stack) {
    if (stack->front1 - stack->tail1 == 0 && stack->front2 - stack->tail2 == 0)
        return true;
    else
        return false;
    }
    
    /* Destroy the stack */
    void stackDestroy(Stack *stack) {
    stack->total = 0;
    stack->front1 = 0;
    stack->tail1 = 0;
    stack->front2 = 0;
    stack->tail2 = 0;
    }

Log in to reply
 

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