gpt4 book ai didi

Java - 自定义链表问题

转载 作者:行者123 更新时间:2023-12-01 19:02:22 26 4
gpt4 key购买 nike

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

最佳答案

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

LinkedList[] lists = new LinkedList[10];

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

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

关于Java - 自定义链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11749817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com