In: Computer Science
Two stacks are the same if they have the same size and their elements at the corresponding positions are the same. Add the method equalStack to class ArrayStack that takes as a parameter ArrayStack object otherStack, and returns true if this stack is the same as otherStack.
Use the following signature for your method: public boolean equalStack(ArrayStack otherStack) { ... }
Please find the below implementation for equalStack method, assuming tthe ArrayStack is extending Stack Class
Also the below code has all the validation checks for null and not used any method variables
public boolean equalStack(ArrayStack otherStack) {
if (this == otherStack)
return true;
if (otherStack == null)
return false;
if (getClass() != otherStack.getClass())
return false;
if (this.size() != otherStack.size())
return false;
while (this.empty() == false) {
if (this.peek() == otherStack.peek()) {
this.pop();
otherStack.pop();
} else
return false;
}
return true;
}