【问题标题】:Java - Custom Linked List IssueJava - 自定义链表问题
【发布时间】:2012-07-29 19:01:15
【问题描述】:

我创建了自己的自定义链接列表(代码如下)。现在,我不明白如何创建像LinkedList[] l = new LinkedList[10] 这样的链接列表的数组。谁能帮帮我。

class Node {
      public int data;
      public Node pointer;
}

class LinkedList {
      Node first;
      int count = 0;

      public void addToEnd(int data){
            if(first == null){
                  Node node = new Node();
                  node.data = data;
                  node.pointer = null;
                  first = node;
                  count = 1;
                  return;
            }
            Node next = first;
            while(next.pointer != null){
                  next = (Node)next.pointer;
            }
            Node newNode = new Node();
            newNode.data = data;
            newNode.pointer = null;
            next.pointer = newNode;
            count++;
      }

      public Node getFirst(){
            return first;
      }
      public Node getLast(){
            Node next = first;
            while(next.pointer != null)
                  next = next.pointer;
            return next;
      }


      public int[] get(){
        if(count != 0){
            int arr[] = new int [count] ;
            Node next = first;
            int i = 0;
                  arr[0]= next.data;
            while(next.pointer != null){
                  next = next.pointer;
                  i++;
                  arr[i] = next.data;
            }
            i++;
            return arr ;
            }
            return null ;
      }
      public int count(){
            return count;
      }
}

【问题讨论】:

  • 您在尝试创建列表时遇到什么错误?
  • new LinkedList[10] 有什么问题?
  • @DougRamsey, LinkedList[] l = new LinkedList[2]; for(int i=0 ; i
  • 可能是 NullPointerException。我会写一个答案来解释原因。或者更确切地说,如果有人不先这样做,我会这样做。
  • @Jeffrey, LinkedList[] l = new LinkedList[2]; for(int i=0 ; i

标签: java


【解决方案1】:

我猜你的问题只是当你创建一个对象数组时,比如

LinkedList[] lists = new LinkedList[10];

你会得到一个充满nulls 的数组;您需要创建要存储在数组中的对象:

for (int i=0; i<lists.length; ++i)
    lists[i] = new LinkedList();

【讨论】:

  • 对于对象数组,我认为声明数组就像拿一堆盒子说“嘿,我要将 存储到这些中。我实际上还没有在其中放入任何东西,但是当我这样做时,它们将是 s"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多