1. Member
Join Date
Mar 2012
Posts
9
Rep Power
0

## Check my answers for a couple of problems

I'm doing practice problems for my test. Could someone check my answers, and help me with the answer if they're wrong?

Problem:

Write a method scaleEach that takes a reference to an IntListElement, list, and an integer, n. The method does not return anything but instead multiples the data field of each element in the list by n. E.g. If the list contained 3, 4, 5, then the call scaleEach(list, 10) would change the list to contain 30, 40, 50.

void scaleEach(IntListElement list, int n){
list.next = list.next*n
}

Problem:

Using the IntListElement class from problem 1, write a method, length, that takes an IntListElement and returns the number of elements in that list. For full credit you should use recursion. A correct non-recursive solution will be worth 2 points.

class IntListElement {
IntListElement(int value) {
data = value;
}
IntListElement next;
int data; }

int length(IntListElement e){
count = 1;
while(e != null){
e = e.next;
count++;
}
return count;
}

Problem:

class IntListElementTest {
public static void main(String[] args) {
IntListElement list = null;
for (int i = 10; i < 14; i++) {
list = new IntListElement(i, list);
}
while (list != null) {
System.out.print(list.data + " ");
list = list.next;
}
}
}

13,12,11,10
*I know the answer for this one, but I want to know why the numbers are printed backwards*

Thank-you.

2. Senior Member
Join Date
Feb 2012
Posts
117
Rep Power
0

## Re: Check my answers for a couple of problems

Did you try running your answers to see if they produce the right output?

1) Wrong. 3,4,5 -> 3,40,5 I believe.
2) That's not recursion.
3) We can't give you that answer without the implementation of intListElement, but I'd bet it has something to do with "list = new IntListElement(i, list);" Think about how a linked list works, that might help you here.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•