Java修改链表数组中的一个Node值

问题描述 投票:0回答:0

目前,我正在尝试使用链表 ADT 和分离链哈希方法实现哈希表。不幸的是,我在尝试删除链接列表中特定索引处的节点时遇到问题,因为当我 x[index] = x[index].next 迭代时,它总是指向相同的地址。我也曾尝试创建一个临时对象来访问,但由于 Java 仅使用“=”赋值执行浅拷贝,因此此方法无济于事。

P/s: 我不允许使用任何额外的java包,例如ArrayList、Set等

这是我的节点类

class studentNode {
    Student student;
    studentNode next;

    studentNode(){}
    studentNode(Student student) {
        this.student = student;
        this.next = null;
    }
}

这是我的哈希表类

class StudentCollection {
    studentNode[] students = new studentNode[13];

    boolean put(Student s) {
        int index = this.hashCode(s.studentId, 13);
        if (students[index] == null) {
            students[index] = new studentNode();
            students[index].next = new studentNode(s);
            return true;
        }
        studentNode tmp = new studentNode(s);
        tmp.next = students[index].next;
        students[index].next = tmp;
        return true;
    }

    public void print(String s) {
        int index = this.hashCode(s, 13);
        while (students[index] != null) {
            System.out.println(students[index].student.studentId + " " + students[index].student.fullName);
            students[index] = students[index].next;
        }
    }

    public Student get(String studentId) {
        int index = this.hashCode(studentId, 13);
        studentNode current = students[index];
        while (current != null) {
            if (current.student.studentId == studentId) {
                System.out.println(current.student.studentId + " " + current.student.fullName);
                return current.student;
            }
            current = current.next;
        }
        System.out.println("Student not found: " + studentId);
        return null;
    }

// This hashfunction is based on the problem requirements.
    public int hashCode(String str, int N) {
        int hashCode = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 65 && str.charAt(i) <= 90) {
                hashCode += str.charAt(i) - 65;
            } else {
                hashCode += str.charAt(i) - 22;
            }
        }
        return hashCode % N;
    }
}

这是我的学生班

class Student {
    String studentId;
    String fullName;
    String major;
    double GPA;

    Student(String studentId, String fullName, String major, double GPA) {
        this.GPA = GPA;
        this.fullName = fullName;
        this.major = major;
        this.studentId = studentId;
    }
}
java algorithm data-structures hash
© www.soinside.com 2019 - 2024. All rights reserved.