Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function that compares two stacks for equality. The function takes two s

ID: 674998 • Letter: W

Question

Write a function that compares two stacks for equality. The function takes two stacks as parameters and returns true if they are identical. The stacks should remain unchanged after the function returns to the calling program. Hint: Either write a friend function that can examine the elements directly, or pop the stacks and save the popped elements so that the stacks can be restored. In this second case, the stack parameters will not be const reference parameters because they are temporarily changed before being restored. As an alternative, the parameters could be value parameters (so that changing them does not affect the actual arguments). Which of the three approaches (friend function, reference parameters, or value parameters) will be most efficient?

Explanation / Answer

Comments added

import java.util.*;

public class StackDemo {

//comparing both stacks
static boolean CheckEqual(Stack st, Stack st2){
if (!st.empty() && !st2.empty()) //checking intitally both stacks
{
try
{
while(st.top().compareTo( st2.top())==0) //checking each element
{
st.pop()
st.otherStack.pop();
}
return false;
}
catch (StackUnderflowException e)
{
return true;
}
}
else
return false;
}

public static void main(String args[]) {
//two stacks created and initialized
Stack st = new Stack();
st.push(1);
st.push(2);
st.push(3);
  
Stack st2 = new Stack();
st2.push(1);
st2.push(2);
st2.push(3);

//calling function
try {
System.out.println(" Stacka are equal: "+CheckEqual(st,st2));
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

--------------------------------------------------------------------------------------------------------------------------------

For friend function...rather than referrence, pass by value parameters is very best one...Since there is no use of altering main stack values...

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote