Name______________________________________________________________
1. (40%) Suppose the following method is added to the public section of your Polynomial class:
int Polynomial::F ()const {
NodePtr rover = Start;
int x = 0;
while (rover != NULL) {
x = x +
(rover->GetCoefficient()* rover->GetExponent());
rover = rover
->GetNext();
if (rover != NULL)
rover =
rover->GetNext();
}
return x;
}
…
What
is output when a client calls F as follows?
void main () {
Polynomial P (“8x8+3x7+3x5+2x4+10x2“);
cout
<< P.F();
}
Output: 99
2. (5%) The method F is const above. What does this imply?
const
implies that F will not change data in the Polynomial object.
3. (40%) Suppose your Polynomial method is augmented as follows:
class Polynomial {
public:
.
.
.
bool DeleteExponent (int InExpToDelete);
.
.
.
};
Implement DeleteExponent, which should delete the term with the exponent given in InExpToDelete. For example, if DeleteExponent(4) is called on the Polynomial object containing 3x5+2x4+109x2 then the term 2x4 will be removed from the Polynomial. You may assume that the Polynomial contains no terms with duplicate exponents.
bool
Stack::DeleteExponent (int
InExpToDelete) {
if (Start == NULL) return false;
else if (Start->GetExponent() == InExpToDelete) {
NodePtr temp = Start;
Start = Start->GetNext();
delete temp;
return true;
}
else {
NodePtr rover = Start;
while ((rover->GetNext() != NULL) && (rover
->GetNext()->GetExponent() != InExpToDelete)) {
rover = rover
->GetNext();
}
if (rover->GetNext() == NULL) return false;
else {
NodePtr temp = rover->GetNext();
rover->SetNext(temp->GetNext());
delete temp;
return true;
}
}
}
4. (5%) In class, I have argued that linked lists are in one sense “better” than static (or dynamic) arrays because linked lists only allocated as much memory as they need at any given time. What is one advantage that arrays (either dynamic or static) have when compared to linked lists?
Note:
Various answers accepted. Some
acceptable answers are:
The code to add or delete an element from an array is simpler than the code to add to or delete from a linked list.
-or-
Arrays are random access data structures; that is, it takes the same amount of time to access the first element as it takes to access the last element. This isn’t true of linked lists: to access the last element, one must generally traverse all previous elements first.