Site icon

Implement two stacks using single array in java (example)

Example – Implement two stacks using single array in java

1.) Initial state of array (Fig 1)

Fig 1: Stack’s top i.e. top1 and top2

2.) Push elements to stack1 (Fig 2)

Fig 2: Push elements to stack1 (increment top1)

3.) Push elements to stack2 (Fig 3)

Fig 3: Push elements to stack2 (decrements top2)

4.) Pop elements to stack1 (Fig 4)

Fig 4: Pop element from Stack1

Program – create two stacks using single array in java

1.) TwoStacks Class:

package org.learn;

import java.util.EmptyStackException;

public class TwoStacks {
    private int arr[];
    private int size;
    private int index1;
    private int index2;

    public TwoStacks(int size) {
        this.size = size;
        arr = new int[size];
        index1 = -1;
        index2 = size;
    }

    public void push1(int element) {
        if (isFull()) {
            throw new StackOverflowError("TwoStacks is full");
        }

        arr[++index1] = element;
    }

    public void push2(int element) {
        if (isFull()) {
            throw new StackOverflowError("TwoStacks is full");
        }

        arr[--index2] = element;
    }

    public int pop1() {
        if (isEmpty1()) {
            throw new EmptyStackException();
        }
        int element = arr[index1];
        index1--;
        return element;
    }

    public int pop2() {
        if (isEmpty2()) {
            throw new EmptyStackException();
        }
        int element = arr[index2];
        index2++;
        return element;
    }

    public boolean isEmpty1() {
        if (index1 == -1) {
            return true;
        }
        return false;
    }

    public boolean isFull() {
        if (index1 == index2) {
            return true;
        }
        return false;
    }

    public boolean isEmpty2() {
        if (index2 == size) {
            return true;
        }
        return false;
    }
}

2.) StackClient:

package org.learn;

public class StackClient {

    public static void main(String[] args) {
        TwoStacks twoStacks = new TwoStacks(5);
        twoStacks.push1(5);
        twoStacks.push1(4);
        twoStacks.push2(3);
        twoStacks.push2(2);
        twoStacks.push2(1);

        System.out.printf("1. Pop elements from stack1 : ");
        while (!twoStacks.isEmpty1()) {
            System.out.printf(" %d", twoStacks.pop1());
        }

        System.out.printf("\n2. Pop elements from stack2 : ");
        while (!twoStacks.isEmpty2()) {
            System.out.printf(" %d", twoStacks.pop2());
        }
    }
}

Output – create two stacks using single array in java

1. Pop elements from stack1 :  4 5
2. Pop elements from stack2 :  1 2 3
Exit mobile version