2 Question 1 For this question, you must implement the class (static) method boo
ID: 3854426 • Letter: 2
Question
2 Question 1 For this question, you must implement the class (static) method boolean isSkipped (Stack s1, Stack s2) . The method isSkipped returns true if and only if the stacks designated by s1 and s2 contain the same elements, in the same order, but with elements 2,4,6,. . . missing in s2. Given sl designating a stack containing the ele- ments 1,2,3,4,5,6,7, where 7 is the top element, and s2 designating a stack containing the elements 1,3,5,7, where 7 is the top element, isSkipped (s1, s2) returns true. . Both stacks, designated by sl and s2, must remain unchanged following a call to the method isSkipped. Specifically, given sl and s2, two refer- ence variables designating stacks, following the call isSkipped(s1, s2), sl contains the same elements, in the same order, as it did before the call to isSkipped. Similarly, s2 contains the same elements, in the same order, as it did before the call to isSkipped. . You can assume that both, sl and s2, will not be null. » An empty stack is considered the skipped version of another empty stack. . The parameters of the method isSkipped are of type Stack, which is an interface For this question, there is an interface named Stack:Explanation / Answer
Here is the answer to the question. If the answer helped, request you to rate it . Thank you.
public static boolean isSkipped(Stack s1, Stack s2)
{
//tempororary arrays to save the contents of the 2 stacks
Stack temp_s1 = new DynamicStack();
Stack temp_s2 = new DynamicStack();
while(!s1.empty() && !s2.empty())
{
if(s1.peek().equals(s2.peek())) //when both the tops match , pop both and save the elements
{
temp_s1.push(s1.pop());
temp_s2.push(s2.pop());
}
else //top of s1 is not matching s2, so skip an element from s1 and save it
{
temp_s1.push(s1.pop());
}
}
boolean ret ;
//at the end , if both are empty, them s1 can be skipped to get s2, return true, otherwise false.
if(s1.empty() && s2.empty())
ret = true;
else
ret = false;
//restore back the contents in both using the saved temporary arrays
while(!temp_s1.empty())
s1.push(temp_s1.pop());
while(!temp_s2.empty())
s2.push(temp_s2.pop());
return ret;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.