I have implemented three stacks in a single array in Java. Any advice on object oriented design, coding structure, logical part or any sort of advice would be appreciated.
public class ThreeStack {
private int[] stack;
private int first, last, mid;
private final int midPosition;
public ThreeStack(int size) {
stack = new int[size];
first = -1; last = size; mid = (first + last) >> 1;
midPosition = mid;
}
//push
public boolean pushFirstStack(final int val) {
if (first + 1 < midPosition) {
stack[++first] = val;
return true;
} else {
return false;
}
}
public boolean pushSecondStack(final int val) {
if (mid + 1 < last) {
stack[++mid] = val;
return true;
} else {
return false;
}
}
public boolean pushThirdStack(final int val) {
if (last - 1 > mid) {
stack[--last] = val;
return true;
} else {
return false;
}
}
//pop
public int popFirstStack() {
if (first < 0) {
return Integer.MIN_VALUE;
} else {
int val = stack[first];
stack[first--] = 0;
return val;
}
}
public int popSecondStack() {
if (mid < midPosition) {
return Integer.MIN_VALUE;
} else {
int val = stack[mid];
stack[mid--] = 0;
return val;
}
}
public int popThirdStack() {
if (last >= stack.length) {
return Integer.MIN_VALUE;
} else {
int val = stack[last];
stack[last++] = 0;
return val;
}
}
//size
public int firstStackSize() {
return mid - midPosition;
}
public int secondStackSize() {
return last - mid;
}
public int lastStackSize() {
return secondStackSize();
}
public void printStack() {
for (int i = 0; i < stack.length; i++) {
System.out.print(stack[i]);
System.out.print((i == first || i == mid || i == last) ? "*": "");
System.out.print(" ");
}
System.out.println();
}
}
Main Method
public class MainClass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ThreeStack stack = new ThreeStack(12);
while (true) {
stack.printStack();
menu();
int c = in.nextInt();
switch (c) {
case 1:
stack.pushFirstStack(in.nextInt());
break;
case 2:
stack.pushSecondStack(in.nextInt());
break;
case 3:
stack.pushThirdStack(in.nextInt());
break;
case 4:
printPopVal(stack.popFirstStack());
break;
case 5:
printPopVal(stack.popSecondStack());
break;
case 6:
printPopVal(stack.popThirdStack());
break;
}
}
}
static void menu() {
System.out.println("+------------------------------+");
System.out.println("1 -> push first stack");
System.out.println("2 -> push second stack");
System.out.println("3 -> push third stack");
System.out.println("4 -> pop first stack");
System.out.println("5 -> pop second stack");
System.out.println("6 -> pop third stack");
System.out.println("+------------------------------+");
}
static void printPopVal(int val) {
System.out.println("Pop : " + val);
}
}
ThreeStack
is. \$\endgroup\$ThreeStack
in more oo and optimized way. That is way I posted in here to get a better idea in design as well as in performance. If you would provide any better design or optimization that will be appreciated. :) \$\endgroup\$