HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Implementing two stacks using single array in java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayjavatwostackssingleusingimplementing

Problem

Please review the code

package com.gmail.practice;

import java.util.Arrays;

public class StacksForTwo {

    int size;
    int[] stack;
    int top1;
    int top2;

    public StacksForTwo(int arraysize)
    {
        size = arraysize;
        stack = new int[size];
        top1 = -1;
        top2 = size;        
    }

    public void push1(int x)
    {
        if(top1 = 0)
        {
            top1--;
            System.out.println("The popped out number is"+" "+stack[top1+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void pop2()
    {
        if(top2 < size)
        {
            top2++;
            System.out.println("The popped out number is"+" "+stack[top2+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void display()
    {
        System.out.println(Arrays.toString(stack));
    }

    public static void main(String[] args)
    {
        StacksForTwo sft = new StacksForTwo(10);
        sft.push1(4);
        sft.push1(5);
        sft.push1(3);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.display();
        sft.push2(8);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.push2(8);
        sft.display();
    }
}

Solution

I would go for

interface Stack {
    boolean isEmpty();
    int pop();
    void push(int x);
}


And then make a class providing two Stacks.

Also create a counter to detect when both stacks are full. This can be done with an AtomicInteger (thread-safeness) counting the free array slots.

public class StackPair {
    public final Stack firstStack = new Stack { ... };
    public final Stack secondStack = new Stack { ... };
    public StackPair(int capacity) { ... }


In StackPair the single array and an AtomicInteger freeEntries. In both Stack implementations access to the array and freeEntries.

Code Snippets

interface Stack {
    boolean isEmpty();
    int pop();
    void push(int x);
}
public class StackPair {
    public final Stack firstStack = new Stack { ... };
    public final Stack secondStack = new Stack { ... };
    public StackPair(int capacity) { ... }

Context

StackExchange Code Review Q#106598, answer score: 7

Revisions (0)

No revisions yet.