Implement Queue using Stacks

Reference:

  1. Implement Queue using Stacks

struct Node{
    int data;
    struct Node *next;
};

struct Queue{
    struct Node *stack1;
    struct Node *stack2;
};

void push(struct Node **top, int data) {

    struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));

    if(new_node == NULL) {
        printf("Stack Overflow");
        return;
    }

    new_node->data = data;
    new_node->next = *top;
    *top = new_node;
}

int pop(struct Node **top) {
    int data;
    struct Node *t;

    if(*top == NULL) {
        printf("Stack Overflow");
        exit(0);
    }

    t = *top;
    data = t->data;
    *top = t->next;

    free(t);
    return data;
}

void enqueue(struct Queue *queue, int data) {
    push(&queue->stack1, data);
}

int dequeue(struct Queue *queue) {

    if(queue->stack1 == NULL && queue->stack2 == NULL) {
        printf("Queue is empty");
        exit(0);
    }

    if(queue->stack2 == NULL) {
        while(queue->stack1 != NULL) {
            push(&queue->stack2, pop(&queue->stack1));
        }
    }
    return pop(&queue->stack2);
}

results matching ""

    No results matching ""