(data structures and other objects using c++) Write a function that compares two
ID: 3687764 • Letter: #
Question
(data structures and other objects using c++) Write a function that compares two stacks for quality. 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 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
Answer for Question:
This below code is written have the comparison of two stacks elements with identical function.
The best way method is
The value parameter or pass by value approach is probably the most efficient because you will have to make a copy at some point to leave the originals unchanged.
Assume the stacks are stacks of integers in this problem.
#include <stack>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
bool compareStacks(stack<int> s1, stack<int> s2){
if(s1.size() == s2.size()){
while(s1.size() != 0){
if(s1.top() == s2.top()){
s1.pop();
s2.pop();
}
else
break;
}
if(s1.empty() && s2.empty()){
return true;
}
else{
return false;
}
}
else
return false;
}
int main()
{
stack<int> s1;
stack<int> s2;
s1.push(5);
s1.push(3);
s1.push(5);
s1.push(3);
s1.push(5);
s2.push(5);
s2.push(5);
s2.push(5);
s2.push(5);
s2.push(5);
bool answer = compareStacks(s1, s2);
if(answer){
cout << "These two stacks are the same." << endl;
}
else{
cout << "These two stacks are not the same." << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.