Write a method that takes as parameters two sorted stacks of integers sl and s2 (where the lowest value is at the top) and returns a sorted stack (lowest on top) that contains the values of both sl and s2. You are allowed to use only the stack operations such as pop, push, and top. You are allowed to use only stacks as temporary storage. No other data structures such as arrays are allowed. The header of the method is: public static Stack merge SortedStacks (Stack si, Stack s2) Write a main method in which you create two sorted stacks and call the above method to test it.

30 0

Get full Expert solution in seconds

$1.97 ONLY

EXPERT ANSWER

Answer :

stack<int> mergeSortedStacks(stack<int> s1, stack<int> s2)
{
stack<int> s;
while (!s1.empty() && !s2.empty())
{
if (s1.top() <= s2.top())
{
s.push(s1.top());
s1.pop();
}
else
{
s.push(s2.top());
s2.pop();
}
}
while (!s1.empty())
{
s.push(s1.top());
s1.pop();
}
while (!s2.empty())
{
s.push(s2.top());
s2.pop();
}
stack<int> ans;
while (!s.empty())
{
ans.push(s.top());
s.pop();
}
return ans;
}

// THIS ANSWER IS IN C++ LANGUAGE