Java - 自定义链接列表问题

时间:2012-07-31 22:15:46

标签: java

我创建了自己的自定义链接列表(代码如下)。现在,我无法理解如何创建像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;
      }
}

1 个答案:

答案 0 :(得分:4)

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

LinkedList[] lists = new LinkedList[10];

你得到一个满是null s的数组;你需要创建存储在数组中的对象:

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