Write a function that compares two stacks for equality. The function takes two s
ID: 3549446 • 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?
For any of your stack implementations, please write a new member function called flip with no parameters. After a stack x
activates flip, x should contain the same items, but the order of those items has been reversed.
Explanation / Answer
1st Question:
Stack Equality: (Linked list implementation)
bool stackEquality( node * top1, node *top2)
{
node *temp1=top1;
node *temp2=top2;
while(*top1 && *top2)
{
if (top1->data==top2->data)
{
top1=top1->next;
top2=top2->next;
}
else
{
top1=temp1;
top2=temp2;
return false;
}
}
if(*top1 && *top2)
{
top1=temp1;
top2=temp2;
return true;
}
else
{
top1=temp1;
top2=temp2;
return false;
}
}
2nd Question:
Reverse Stack( Array implementation )
void flip()
{
int flipStack[top]; // the required stack
int temp=top, k=0;
while(temp!=-1)
{
flipStack[k++]=stacks[temp--]; //stacks is the original stack
}
temp=top;
k=0;
while(k!=temp)
{
stacks[k]=flipStack[k];
k++;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.