C 0ms solution with two stacks

• ``````typedef struct {
int *stack1,*stack2;
int top1,top2;
} Queue;

/* Create a queue */
void queueCreate(Queue *queue, int maxSize) {
queue -> stack1 = (int*) malloc (sizeof(int)*maxSize);
queue -> stack2 = (int*) malloc (sizeof(int)*maxSize);
queue -> top1 = -1;
queue -> top2 = -1;
}

/* Push element x to the back of queue */
void queuePush(Queue *queue, int element) {
/*add element x using push to top operation*/
(queue->stack1)[++(queue->top1)] = element;
}

/* Removes the element from front of queue */
void queuePop(Queue *queue) {
/* puts all the stack1 elements(except the front elemt)  to stack2*/
while ( (queue->top1) > 0 )
(queue->stack2)[++(queue->top2)] = (queue->stack1)[(queue->top1)--];

/* removes the element from front using pop from top operation */
(queue->top1)--;

/* puts all the elements in stack2 back to stack1 */
while ( (queue->top2) >= 0) {
(queue->stack1)[++(queue->top1)] = (queue->stack2)[(queue->top2)--];
}
}

/* Get the front element */
int queuePeek(Queue *queue) {

/* puts all the stack1 elements(except the front elemt) to stack2*/
while ( (queue->top1) > 0 )
(queue->stack2)[++(queue->top2)] = (queue->stack1)[(queue->top1)--];

/* get the front element */
int temp = (queue->stack1)[(queue->top1)];

/* puts all the elements in stack2 back to stack1 */
while ( (queue->top2) >= 0)
(queue->stack1)[++(queue->top1)] = (queue->stack2)[(queue->top2)--];

return temp;
}

/* Return whether the queue is empty */
bool queueEmpty(Queue *queue) {
/* using is empty operation */
return (queue->top1) < 0;
}

/* Destroy the queue */
void queueDestroy(Queue *queue) {
queue == NULL;
}``````

• Only one stack is needed. Make it circular.

• so this is why you don't vote this solution?

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