Answer to Question #263944 in C for Ate

Question #263944

Write a program to implement 2 Stacks in a single array of size N. The stacks

should not show overflow if there even a single slot available in the array. Write

the functions popA(), popB(), pushA(), pushB() for pushing and popping from

these stacks.


1
Expert's answer
2021-11-12T00:07:38-0500
#include <stdio.h>
#include <stdlib.h>


typedef struct DoubleStak_ {
    int* values;
    int size;
    int topA;
    int topB;
} DoubleStack;


DoubleStack* initDoubleStack(int size);
void freeDoubleStack(DoubleStack* stack);
int popA(DoubleStack* stack);
int popB(DoubleStack* stack);
void pushA(DoubleStack* stack, int x);
void pushB(DoubleStack* stack, int x);
int emptyA(DoubleStack* stack);
int emptyB(DoubleStack* stack);
int isFull(DoubleStack* stack);


int main() {
    DoubleStack* stack = initDoubleStack(10);


    for (int i=1; i<=5; i++) {
        pushA(stack, i);
        pushB(stack, -i);
    }


    for (int i=0; i<5; i++) {
        int x = popB(stack);
        pushA(stack, x);
    }


    while (!emptyA(stack)) {
        int x = popA(stack);
        printf("%d ", x);
    }
    printf("\n");


    freeDoubleStack(stack);
}


DoubleStack* initDoubleStack(int size) {
    DoubleStack* stack = (DoubleStack *) malloc(sizeof(DoubleStack));
    stack->values = (int *) malloc(sizeof(int) * size);
    stack->size = size;
    stack->topA = 0;
    stack->topB = size-1;
    return stack;
}


void freeDoubleStack(DoubleStack* stack) {
    free(stack->values);
    free(stack);
}


int popA(DoubleStack* stack) {
    if (stack->topA == 0) {
        fprintf(stderr, "Error: popA from empty steck\n");
        exit(1);
    }
    return stack->values[--stack->topA];
}


int popB(DoubleStack* stack) {
    if (stack->topB == stack->size-1) {
        fprintf(stderr, "Error: popB from empty steck\n");
        exit(1);
    }
    return stack->values[++stack->topB];
}


void pushA(DoubleStack* stack, int x) {
    if (stack->topA > stack->topB) {
        fprintf(stderr, "Error: pushA in full stack\n");
        exit(1);
    }
    stack->values[stack->topA++] = x;
}


void pushB(DoubleStack* stack, int x) {
    if (stack->topA > stack->topB) {
        fprintf(stderr, "Error: pushB in full stack\n");
        exit(1);
    }
    stack->values[stack->topB--] = x;
}


int emptyA(DoubleStack* stack) {
    return stack->topA == 0;
}


int emptyB(DoubleStack* stack) {
    return stack->topB == stack->size-1;
}


int isFull(DoubleStack* stack) {
    return stack->topA > stack->topB;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS