Solved

reflist / unsortedlinkedlist help / linked list

Posted on 2008-10-23
5
570 Views
Last Modified: 2013-11-23
Hey all i am trying to figure out how to get this RefList working for me...

    Implement a method countValue() that counts the number of times an item occurs in a linked list.

    int countValue(RefList f, int item);

    Generate 20 random numbers in the range of 0 to 4, and insert each number at the front of a linked list. Output the list by using a method which you would call writeLinkedList which you would add to the RefList.java program. In a loop, call the method countValue() , and display the number of occurrences of each value from 0 to 4 in the list.

 * Declare an unsortedlinkedlist unlist.
    * use a for loop in which you will do the following 20 times:
         1. create a random number between 0 and 4
         2. insert the number into the unlist
    * print the elements in unlist.
    * call the countValue method 5 times where each time you will send 2 parameters:
         1. the unlist
         2. the value of an int that is 0,1,2,3,4
    * write the countValue method which accomplishes the followings:
         1. it has 2 parameters:
                o the unlist
                o an int i
         2. declare an int counter a.
         3. make a list element out of the element i, say f2.
         4. declare a for loop that will run 20 times in which you will do the following:
                o get the first element from the unlist, say f1.
                o make sure you compare f1 to f2.
                o if they are equal increment the counter a.
         5. return a.
         6. done

But there's an error for the "refl1.add(intRandomNum);" since the RefList class does not have a "add" property. How am i supposed to add to a list that has no command to add? And i dont even have the code for the "unsortedlinkedlist" it asks to Declare ????
So far this is what i have:

 

***** PREX6.java *****

 

public class PREX6

    {

           public static void main(String[] args)

           {

              RefList refl1= new RefList();

              int intRandomNum = 0;

              int count = 0;

     

              while (count != 21)

              {

                    intRandomNum = (int)(Math.random() * 5);

                    refl1.add(intRandomNum);

              }

     

              System.out.println(refl1);

          }

    }

 

**** RefList.java *****

public class RefList

    {

      protected int numElements;          // number of elements in this list

      protected LLObjectNode currentPos;  // current position for iteration

     

      // set by find method

      protected boolean found;         // true if element found, else false

      protected LLObjectNode location; // node containing element, if found

      protected LLObjectNode previous; // node preceeding location

     

      protected LLObjectNode list;     // first node on the list

     

      public RefList()

      {

        numElements = 0;

        list = null;

        currentPos = null;

      }

    protected void find(Object target)

      // Searches list for an occurence of an element e such that

      // e.equals(target). If successful, sets instance variables

      // found to true, location to node containing e, and previous

      // to the node that links to location. If not successful, sets 

      // found to false.

      {

        boolean moreToSearch;

        location = list;

        found = false;

     

        moreToSearch = (location != null);

        while (moreToSearch && !found) 

        {

          if (location.getInfo().equals(target))  // if they match

           found = true;

          else

          {

            previous = location;

            location = location.getLink();

            moreToSearch = (location != null);

          }

        }

      }

    public int size()

      // Returns the number of elements on this list. 

      {

        return numElements;

      }

     

      public boolean contains (Object element)

      // Returns true if this list contains an element e such that 

      // e.equals(element); otherwise, returns false.

      {

        find(element);

        return found;

      }

    public boolean remove (Object element)

      // Removes an element e from this list such that e.equals(element)

      // and returns true; if no such element exists, returns false.

      {

        find(element);

        if (found)

        {

          if (list == location)     

            list = list.getLink();    // remove first node

          else

            previous.setLink(location.getLink());  // remove node at location

     

          numElements--;

        }

        return found;

      }

     

      public Object get(Object element)

      // Returns an element e from this list such that e.equals(element);

      // if no such element exists, returns null.

      {

        find(element);    

        if (found)

          return location.getInfo();

        else

          return null;

      }

    public String toString()

      // Returns a nicely formatted string that represents this list.

      {

        LLObjectNode currNode = list;

        String listString = "List:\n";

        while (currNode != null)

        {

          listString = listString + "  " + currNode.getInfo() + "\n";

          currNode = currNode.getLink();

        }

        return listString;

      }  

     

      public void reset()

      // Initializes current position for an iteration through this list,

      // to the first element on this list.

      {

        currentPos  = list;

      }

    public Object getNext()

      // Preconditions: The list is not empty

      //                The list has been reset

      //                The list has not been modified since most recent reset

      //

      // Returns the element at the current position on this list.

      // If the current position is the last element, then it advances the value 

      // of the current position to the first element; otherwise, it advances

      // the value of the current position to the next element.

      {

        Object next = currentPos.getInfo();

        if (currentPos.getLink() == null)

          currentPos = list;

        else

          currentPos = currentPos.getLink();

        return next;

      }

    }

Open in new window

0
Comment
Question by:Stealthrt
  • 3
  • 2
5 Comments
 
LVL 3

Expert Comment

by:willyRD
ID: 22794404
Hello,

This seems homework, so here we can not solve it for you, but we can help you.
As RefList doesn't have an add method you have an error, you'll probably have to implement it.

Have a look at these Java interfaces and classes that may give you help to implement your RefList:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html
http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html
http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html
and an explanation of a linked list:
http://www.mycsresource.net/articles/programming/data_structures/linkedlists


0
 

Author Comment

by:Stealthrt
ID: 22805636
Thanks for the links willyRD but they did not help much.

how about this:
public void add(Object element)

  // Adds element to this list.

  {

    //LLObjectNode currNode = list;

    //list = element;
 

    LLObjectNode temp = new LLObjectNode(element);

    LLObjectNode current = head;
 

    // starting at the head node, crawl to the end of the list

    while(current.getNext() != null)

    {

       current.setNext(new LLNode(obj));

    }

    // the last node's "next" reference set to our new node

    current.setNext(temp);

    listCount++;// increment the number of elements variable

  }

Open in new window

0
 
LVL 3

Accepted Solution

by:
willyRD earned 125 total points
ID: 22812813
Hello,

I think that there's a little confusion here, the unsortedlinkedlist seems to me that it's the same as RefList, as RefList it's an implementation of an unsorted linked list.
The idea of the add method seems correct, but you'll have to solve some compilation problems, as the name of the variables is not the same as in the RefList.java; example: listCount probably refers to numElements.
Once you have corrected these errors you'll be able to implement the countValue method.

If you have any more problems you can write them here.

Best regards,
willyRD
0
 

Author Comment

by:Stealthrt
ID: 22816085
Got it working:

import java.util.Random;

import java.lang.Integer;
 

public class P

{

  public static void main(String[] args)

  {

    int intTempRandom;

    int intItem;

    String strRandomNumbers = "";

    Random random_numbers = new Random();

    RefUnsortedList myList = new RefUnsortedList();
 

    for (int i = 0; i < 20; i++)

    {

      intTempRandom = random_numbers.nextInt(5);

      strRandomNumbers = intTempRandom + "," + strRandomNumbers;

      intItem = new Integer(intTempRandom);

      myList.add(intItem);

    }
 

    myList.reset();

    System.out.println("The random numbers are: " + strRandomNumbers);
 

    for (int i=0;i<=4; i++)

    {

      intTempRandom = countValue(myList, i);

      System.out.println(i + ": " + intTempRandom);

    }

  }
 

  public static int countValue(RefUnsortedList f, int v)

  {

    int theList = 0;

    int theCount = 0;
 

    for (int a = 0; a < 20; a++)

    {

      theList = (Integer)f.getNext();
 

      if (theList == v)

      {

        theCount++;

      }

    }

    return (theCount);

  }

}

Open in new window

0
 
LVL 3

Expert Comment

by:willyRD
ID: 22819891
Hello,

I think that I have helped in this question and It wouldn't be fair to leave it as closed.
Let's review the facts:
1) these question clearly seems homework so I haven't posted a solution, only guidelines so that Stealthrt could advance in solving the question.
2) in response to the code of the "add" method, I think that my response is right and helpful.

It's right that the final solution it's correct (incomplete, but correct), but I think that my answers have been helpful, so I demand that a moderator reviews this question and considers if I have helped or not.

Best Regards
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now