Skip to content
Advertisement

How would I find the length of a linkedlist IN a linkedlist?

I’m trying to go through a linkedlist(which we can call the superlist) which has elements of linked lists(sublists) within it.

The method that adds the elements into both linked lists is:

LinkedList<Object> list = new LinkedList<>();

public void add(Object... item) {
    LinkedList<Object> thingie = new LinkedList<>();
    for (Object i: item) {
        thingie.add(i);
    }
    list.addAll(thingie);
}

Now I have to write methods to check if there are groups of 1, 2, 3, 4 elements in the sublists by traversing the superlist What I have so far (which is very wrong) is:

LinkedList <Object> ohno = new LinkedList<>();
        for (int i = 0; i<list.size(); i++){
            ohno = (LinkedList<Object>) list.get(i);
            if (int j = 1; j = ohno.size();){
                return true;
            }
            else return false;
        }

Advertisement

Answer

What you can do is create a method that passes a parameter for the group size in question and finds out if there are any sub lists of size group size.

private static boolean hasSubListsOfSize (LinkedList<Object> superList, final int groupSize)
{
     for (int i = 0, size = superList.size(); i < size; i++)
     {
         LinkedList<Object> subList = (LinkedList<Object>) superList.get(i);
         if (subList.size() == groupSize)
         {
            return true;
         }
     }

     // didn't find any sub lists of the group size
     return false;
}

Side Note: As pointed out by @Abhishek your super List is technically not a LinkedList of LinkedList's. It is a LinkedList of Objects. That’s why you have to do the explicit cast to LinkedList to access the “Sub LinkedList’s”.

If you want a true LinkedList of LinkedList's, then you should create the superList like this:

LinkedList<LinkedList<Object>> superList = new LinkedList<LinkedList<Object>>();

If you create it that way, then you will avoid having to do the explicit casts at compile time.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement