Assume we already have the Stack Interface code and the class Stack Array code a
ID: 3836304 • Letter: A
Question
Assume we already have the Stack Interface code and the class Stack Array code available. The goal of this program is to write the main code. This code should create two Stack Array objects of type String. You should then place some fruit names in one stack and some fruit names in the other stack. After the names are placed in each stack, then your code should check if the two stacks have the same fruit names in the same order. Note that after the check, the two stacks should have the same original values as before the check started.Explanation / Answer
Given: StackArray class and StackInterface
Lets assume: push(T x), T pop(), boolean isEmpty(), T peek() are the methods in StackArray class
Where T is type of data
// Creating two stacks of string type
StackArray<String> stack1 = new StackArray<String> ();
StackArray<String> stack2 = new StackArray<String> ();
// pushing some items in both stacks
stack1.push("apple");
stack1.push("papaya");
stack1.push("gauva");
// some more items
stack1.push("apple");
stack1.push("pears");
stack1.push("banana");
// some more items
// now comparing items of both stacks in order
// Creating two temporary stack to store content of both stacks
StackArray<String> temp1 = new StackArray<String> ();
StackArray<String> temp2 = new StackArray<String> ();
while(!stack1.isEmpty() && !stack2.isEmpty()){ // till both stack becomes empty
if(stack1.peek().equals(stack2.peek())){ // if current items are same in both stack then pop from
// both stack and put in temp stacks
temp1.push(stack1.pop());
temp2.push(stack2.pop());
}
else{
break; // stop comparing
}
}
// now if both stacks are empty then all contentns of both stack are same
if(stack1.isEmpty() && stack2.isEmpty()){
System.out.println("Content of both stack are same")
}else{
System.out.println("Content of both stack are not same")
}
// now copying the temp contents in original stack again
while(!temp1.isEmpty()){
stack1.push(temp1.pop());
stack2.push(temp2.pop());
}