Results 1 to 2 of 2
  1. #1
    LuluMM is offline Member
    Join Date
    Mar 2012
    Posts
    9
    Rep Power
    0

    Default 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.


    Answer:

    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; }


    Answer:

    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;
    }
    }
    }

    Answer:

    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. #2
    Diargg is offline Senior Member
    Join Date
    Feb 2012
    Posts
    117
    Rep Power
    0

    Default 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.

Similar Threads

  1. Inheritance problems...quick answers if possible :)
    By circuspeanuts in forum New To Java
    Replies: 1
    Last Post: 04-13-2009, 09:06 PM
  2. A couple of problems trying to get solved
    By nick2price in forum New To Java
    Replies: 3
    Last Post: 01-18-2009, 09:21 PM
  3. Couple of newbie questions
    By ananasman in forum New To Java
    Replies: 11
    Last Post: 11-20-2008, 11:54 PM
  4. Couple of Problems
    By joz_12345 in forum Java 2D
    Replies: 2
    Last Post: 03-06-2008, 04:13 PM

Posting Permissions

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