Describe how a single array can be used to implement two stacks.

#include<stdio.h>
#include<stdlib.h>
#define size 10 /* Macro definition */
int top1 = -1, top2 = size; /* Global variable declaration */
int a[size];

int main() {
    int ch, n1, n2;
    while (1) {
        printf("\n=====================\n");
        printf("-- Menu Selection --|\n");
        printf("=====================\n");
        printf("1. Push |\n");
        printf("2. Pop |\n");
        printf("3. Display |\n");
        printf("0. Exit |\n");
        printf("=====================\n");
        printf("Enter choice(0-3):");
        scanf("%d", &ch);
        switch (ch) {
            case 1:
                printf("Enter n1:");
                scanf("%d", &n1);
                push1(n1);
                printf("Enter n2:");
                scanf("%d", &n2);
                push2(n2);
                break;
            case 2:
                pop1();
                pop2();
                break;
            case 3:
                display();
                break;
            case 0:
                printf("Goodbye...!!!!!!\n");
                exit(0);
        }
    }
}

int push1(int n) {
    if (top1 < top2 - 1)
        a[++top1] = n;
    else
        printf("stack1 is full.....!!!!!!\n");
    return 0;
}

int pop1() {
    int x;
    if (top1 >= 0 && top1 < top2) {
        x = a[top1];
        a[top1] = 0;
        top1--;
        printf("%d HASBEEN POPED FROM STACK1.\n", x);
    } else
        printf("stack1 is empty......!!!!!\n");
}

int push2(int n) {
    if (top2 > top1 + 1)
        a[--top2] = n;
    else
        printf("stack2 is full......!!!!!!\n");
    return 0;
}

int pop2() {
    int x;
    if ((top2 < size)&&(top2 > top1)) {
        x = a[top2];
        a[top2] = 0;
        top2++;
        printf("%d HASBEEN POPED.\n", x);
    } else
        printf("stack2 is empty....!!!!\n");
}

int display() {
    int i, j;
    if ((top1 == -1)&&(top2 == size))
        printf("stack is empty.\n");
    else {
        printf("S = ( ");
        for (i = top1; i >= 0; i--)
            printf("%d ", a[i]);
        for (j = top2; j < size; j++)
            printf("%d ", a[j]);
        printf(")\n");
    }
    return 0;
}

Logic:-Here the two stacks will start with minimum index amd maximum index respectively of the array declared and grow towards each other and both the stacks overflow when there will be no space remain in the array.

Popular posts from this blog

8 Bit Plane Slicing of an image in Image Processing

Code to upload multiple files simultaneously using JSP, Servlet .

STRING PALINDROME USING STACK AND QUEUE