简体   繁体   English

如何在链表中找到链表的长度?

[英]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:现在我必须编写方法来通过遍历超级列表来检查子列表中是否有 1、2、3、4 个元素组到目前为止我所拥有的(这是非常错误的)是:

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

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 .边注:正如所指出的@Abhishek你的超级名单在技术上是一个LinkedListLinkedList's It is a LinkedList of Objects .它是ObjectsLinkedList That's why you have to do the explicit cast to LinkedList to access the "Sub LinkedList's".这就是为什么您必须对 LinkedList 进行显式转换才能访问“子 LinkedList”。

If you want a true LinkedList of LinkedList's , then you should create the superList like this:如果你想要一个真正的LinkedListLinkedList's ,那么你应该像这样创建 superList:

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.如果您以这种方式创建它,那么您将避免在编译时进行显式转换。

Recursive simple solution递归简单的解决方案

def getCount(head):
    if (not node): # Base case
        return 0
    else:
        return 1 + getCount(head.next)
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM