CPSC 170 Linked Structures Homework
Below is the summing code we looked at in class. For each of the two pieces of code,
- Determine whether it correctly solves the given problem. Remember that the list pointed to by front may contain 0 or more elements.
- If the code is correct, determine its complexity in big-Oh. If it is not correct, explain what it will do (that is, what the problem is) AND show how to correct it.
Here's the catch: Don't use the computer! These are THINKING exercises.
Write up your answers neatly; you will turn them in at class on Monday.
Here's the code.
-
A loop that sums the elements of a linked list:
sum = 0;
for (LN<Integer> temp=front; temp.getNext()!=null; temp=temp.getNext())
sum += temp.getElement();
-
A recursive method that does the same thing:
int sum(LN<Integer> node)
{
if (node.getNext() == null)
return node.getElement();
else
return node.getElement() + sum(node.getNext());
}