gpt4 book ai didi

java - Java 哈希表单向链表的空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:49:31 24 4
gpt4 key购买 nike

这是提供的初始类,我们无法修改

public class SLL {
public class Node {
private int data;
private Node next;

public Node() {
data = 0;
next = null;
}

public Node(int newData, Node linkValue) {
data = newData;
next = linkValue;
}

public int getData() {
return data;
}

public Node getLink() {
return next;
}
}// End of Node inner class

private Node head;

public SLL() {
head = null;
}

public void addToStart(int itemData) {
head = new Node(itemData, head);
}

public boolean contains(int item) {
return (find(item) != null);
}

/**
* Finds the first node containing the target item, and returns a reference
* to that node. If target is not in the list, null is returned.
*/
public Node find(int target) {
Node position = head;
int itemAtPosition;
while (position != null) {
itemAtPosition = position.data;
if (itemAtPosition == target) {
return position;
}
position = position.next;
}
return null; // target was not found
}

public void outputList() {
Node position = head;
while (position != null) {
System.out.print(position.data + " ");
position = position.next;
}
System.out.println();
}
}

这是我们应该完成以使测试器正常工作的 Set 类,我使用 add 方法不断收到空指针异常,但是,它几乎与我在其他代码(包括我们的文本)中看到的完全一样书。任何见解都将非常感激,因为我的老师有预先制作的幻灯片,并且不会向寻求帮助的学生解释任何内容或提供任何建议。

public class Set {
private SLL[] hashArray; // DO NOT MODIFY THIS LINE
private int size = 10; // DO NOT MODIFY THIS LINE

// DO NOT MODIFY THIS METHOD
public Set() {
hashArray = new SLL[size];
}

// DO NOT MODIFY THIS METHOD
private int computeHash(int s) {
return s % size;
}

// COMPLETE BELOW

public void add(int x)
{
int hash = computeHash(x); // Get hash value
SLL list = hashArray[hash];
if (!list.contains(x))
{
// Only add the target if it's not already
// on the list.
list.addToStart(x);/*replaced hashArray[hash] with list*/
}
}

public void output( )
{
System.out.println("I will work on this later");
}
}

最后,测试人员...

public class Tester{

// Have this method to display your name, instead.
static void displayName(){
System.out.println("Program written by Tony.\n");
}

// DO NOT MODIFY THE MAIN METHOD
public static void main(String[] args){
displayName();
Set set1 = new Set();
Set set2 = new Set();

set1.add(3);
set1.add(3);
set1.add(13);
set1.add(23);
set1.add(4);
set1.add(5);

set2.add(15);
set2.add(6);
set2.add(6);

System.out.println("Contents of set 'set1': ");
set1.output();
System.out.println("Contents of set 'set2': ");
set2.output();
System.out.println();
}
}

最佳答案

我不想直接给出答案,因为这可能是一项家庭作业(如果我错了,请纠正我)。考虑第一次在新构造的集合上调用 add 方法的情况。此时“hashArray”的所有索引中有哪些值,这对于 add 方法中的局部变量“list”意味着什么?

关于java - Java 哈希表单向链表的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28908825/

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