In: Computer Science
Given the two stacks S1 and S2 each with a set of numbers, write an algorithm to check if the two stacks are identical (have the same information). Use only the Push and Pop operations. The original stacks should be kept. Briefly explain the time complexity of your algorithm.
Algorithm:
Function implementing whether two stacks are equal or not:
static boolean isSameStack(Stack<String> stack1,
Stack<String> stack2)
{
// Create a flag variable
boolean flag = true;
// Check if size of both stacks are same
if (stack1.size() != stack2.size())
{
flag = false;
return flag;
}
// Until the stacks are not empty
// compare top of both stacks
while (stack1.empty() == false)
{
// If the top elements of both stacks
// are same
if (stack1.peek() == stack2.peek())
{
// Pop top of both stacks
stack1.pop();
stack2.pop();
}
else
{
// Otherwise, set flag to false
flag = false;
break;
}
}
// Return flag
return flag;
}