The goal of this assignment is to complete question 15 in your textbook on stack
ID: 3824996 • Letter: T
Question
The goal of this assignment is to complete question 15 in your textbook on stacks. You must use the authors node2.h, node2.template, stack4.h and stack4.template
You can find the node files here: https://www.cs.colorado.edu/~main/chapter6/
You can find the stack files here: https://www.cs.colorado.edu/~main/chapter7/
Problem 15 states: For any of your stack implementations, please write a new member function called swap with one reference parameter that is also a stack. After calling x.swap(y), the value of x should equal the original value of y and vice versa. Make sure to print out the values before the swap and after the swap as well
Explanation / Answer
Solution:
void swap(stack& val_y)
{
int val_f=1;
if(!Empty()) //if val_x is not empty
{
for (int val_i = 0; val_i<=val_y.top; val_i++) //take out element from val_y
{
int val_t=val_y.elements[val_i];
for(int val_k=0;val_k<=top;val_k++) //check availability of elments in val_x
{
if(elements[val_k]==val_t) //element available in val_x then no need to insert element
{
val_f=0;
break;
}
}
if(val_f==1)//element is not available then insert element into val_x
{
push(val_t);
}
}
//take val_y stack and take each element from val_x
for (int val_i = 0; val_i<=top; val_i++)
{
int val_t=elements[val_i];
for(int val_k=0;val_k<=val_y.top;val_k++)
{
//if element is present then no need to insert
if(val_y.elements[val_k]==val_t)
{
val_f=0;
break;
}
}
if(val_f==1)//otherwise insert into val_y
{
val_y.push(val_t);
}
}
}
else//if val_x is empty
{
(this)->top = val_y.top; //(this).top represents stack val_x top
//inserting element
for (int val_i = 0; val_i<=val_y.top; val_i++)
{
int val_t=val_y.elements[val_i];
push(val_t);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.