【问题标题】:Checking if value in linked list is equal to String at each node检查链表中的值是否等于每个节点的字符串
【发布时间】:2018-04-17 18:57:55
【问题描述】:

我正在为家庭作业编写一个程序,该程序具有一个二叉搜索树(名册),学生对象通过其字符串 ID 插入到该树中。每个学生都有一个链接列表,他们的课程被添加到其中包含课程的字符串和他们的成绩。二叉搜索树是我自己的实现版本。

我无法实现打印所有包含特定课程的学生的方法。我认为我的 printCourseHelper() 方法中的实现已关闭,因为 if 条件无法正常工作以检查每个节点的列表中的值是否等于给定值。

我正在查找所有学生在“Math161”课程中注册的课程,该课程应为 3,并且将打印该课程中学生的字符串 ID。当我运行我的程序时,我没有收到任何错误,但是只有在我的 displayStudents() 上方调用的函数正在打印。

我认为我的问题在于我的 BST.java、printCourse 和 printCourseHelper 方法:

public void printCourse(String course) {
        printCourseHelper(root, course);
    }

    public void printCourseHelper(Node n, String course) {        
        if(n.element.getCourseList().contains(course)) {
            System.out.print(n.element.getId() + " ");
        }

        if (n.left != null) {
            printCourseHelper(n.left, course);
        }    
        if (n.right != null) {
            printCourseHelper(n.right, course);
        }     
    }

Homework5.class/main:

import java.util.LinkedList;

public class Homework5 {

    static Roster rost = new Roster();

    public static void main(String[] args) {
        addStudent();
        displayAllStudents();
        lookupStudent("11114");
        addCourse();
        displayStudents("Math161");
    }

    // add students to the roster
    static void addStudent() {
        rost.addStudent(new Student("11111", "Jon", "Benson"));
        rost.addStudent(new Student("11112", "Erick", "Hooper"));
        rost.addStudent(new Student("11113", "Sam", "Shultz"));
        rost.addStudent(new Student("11114", "Trent", "Black"));
        rost.addStudent(new Student("11115", "Michell", "Waters"));
        rost.addStudent(new Student("11116", "Kevin", "Johnson"));
    }

    // display all students in the roster
    static void displayAllStudents() {
        rost.displayAllStudents();
    }

    // lookup a student in the roster
    static void lookupStudent(String id) {
        if (rost.find(id) != null) {
            System.out.println(id + " found");
        } else {
            System.out.println(id + " not found");
        }
    }

    // add courses to the roster
    static void addCourse() {
        rost.addCourse("11111", new Course("CS116", 80));
        rost.addCourse("11111", new Course("Math161", 90));
        rost.addCourse("11112", new Course("Math161", 70));
        rost.addCourse("11112", new Course("CS146", 90));
        rost.addCourse("11112", new Course("CS105", 85));
        rost.addCourse("11113", new Course("CS216", 90));
        rost.addCourse("11114", new Course("CIS255", 75));
        rost.addCourse("11114", new Course("CS216", 80));
        rost.addCourse("11114", new Course("Math161", 60));
        rost.addCourse("11114", new Course("COMM105", 90));
    }

    // display students enrolled in a given course id
    static void displayStudents(String courseId) {
        rost.displayStudents(courseId);
    }

    // display courses taken by a student
    static void displayCourses(String id) {
        rost.displayCourses("id");
    }

    // display the average grade for a student
    static void getCourseAverage(String courseId) {
        rost.getCourseAverage(courseId);
    }

    // display the average grade for a student
    static void dropCoursesBelow(String id, int grade) {
        rost.dropCoursesBelow(id, grade);
    }

    // drop a course from a student
    static void dropCourse(String id, String courseId) {
        rost.dropCourse(id, courseId);
    }

    // change the grade for a student
    static void changeGrade(String id, String courseId, int grade) {
        rost.changeGrade(id, courseId, grade);
    }
}

学生班

class Student implements Comparable<Student> {

    String id;
    String firstName;
    String lastName; 
    LinkedList<Course> courses = new LinkedList<>();

    Student(String id, String fName, String lName) {
        this.id = id;
        this.firstName = fName;
        this.lastName = lName;
    }

    public String getName() {
        return lastName;
    }

    public void setName(String lName) {
        this.lastName = lName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int compareTo(Student other) {    
        return this.getId().compareTo(other.getId());
    }

    public void addCourse(Course course) {
        courses.add(course);
    }

    public LinkedList<Course> getCourseList() {
        return courses;
    } 
}

课程.class:

class Course {

    LinkedList<Course> course = new LinkedList<>();   
    String id;  // course id
    int grade;

    Course(String id, int grade) {
        this.id = id;
        this.grade = grade;
    }

    public String getCourseId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getGrade() {
        return grade;
    }

    public void setId(int grade) {
        this.grade = grade;
    }

}

名册.class:

class Roster {

    Student root;
    int numStudents;
    BST<Student> roster = new BST<>();
    LinkedList<Course> courseList = new LinkedList<>();

    public Roster() {
        root = null;
        numStudents = 0;
    }

    public void addStudent(Student st) {
        roster.insert(st);
        numStudents++;
    }

    public void displayAllStudents() {
        roster.traverse(2);
    }

    public Student find(String id) {
        return roster.find(id);
    }

    public void addCourse(String id, Course course) {
        Student student = roster.find(id);
        student.addCourse(course);      
    }

    public void displayStudents(String courseId) {
        roster.printCourse(courseId);
    }
}

BST.java

class BST<Roster extends Comparable> {

    private Node root;

    public BST() {
        root = null;
    }

    // Generic find method
    public Student find(String id) {  
        Node current = root;
        // Loop until e.compare to current element is not equal to 0
        while (id.compareTo(current.element.getId()) != 0) {
            //!!! implement
            // if e.compare is less than 0 set current to current.left
            if (id.compareTo(current.element.getId()) < 0) {
                current = current.left;
            } // else if current is 0 or greater than 0 set current 
            // to current.right
            else {
                current = current.right;
            }
            // if current is null, return null
            if (current == null) {
                return null;
            }
        }
        // return current value when loop ends
        return current.element;    
    }

    public void insert(Student st) {
        Node newNode = new Node(st);
        if (root == null) {
            root = newNode;
        } else {
            Node current = root;
            Node parent = null;
            while (true) {
                parent = current;
                if (st.getId().compareTo(current.element.getId()) < 0) {
                    current = current.left;
                    if (current == null) {
                        parent.left = newNode;
                        return;
                    }
                } else {
                    current = current.right;
                    if (current == null) {
                        parent.right = newNode;
                        return;
                    }
                }
            }
        }
    }

    public void printCourse(String course) {
        printCourseHelper(root, course);
    }

    public void printCourseHelper(Node n, String course) {
        if(n.element.getCourseList().contains(course)) {
            System.out.print(n.element.getId() + " ");
        }
        if (n.left != null) {
            printCourseHelper(n.left, course);
        }
        if (n.right != null) {
            printCourseHelper(n.right, course);
        }   
    }

    public void traverse(int traverseType) {
        switch (traverseType) {
            case 1:
                System.out.print("\nPreorder traversal: ");
                // call preOrder(root) and implement preOrder()
                preOrder(root);
                break;
            case 2:
                System.out.print("\nList of all students:  ");
                inOrder(root);
                break;
            case 3:
                System.out.print("\nPostorder traversal: ");
                // call postOrder(root) and implement postOrder()
                postOrder(root);
                break;
        }
        System.out.println();
    }

    private void inOrder(Node localRoot) {
        if (localRoot != null) {
            inOrder(localRoot.left);
            System.out.print(localRoot.element.getId() + " ");
            inOrder(localRoot.right);
        }
    }

    private void preOrder(Node localRoot) {
        if (localRoot != null) {
            System.out.print(localRoot.element + " ");
            preOrder(localRoot.left);
            preOrder(localRoot.right);
        }
    }

    private void postOrder(Node localRoot) {
        if (localRoot != null) {
            postOrder(localRoot.left);
            postOrder(localRoot.right);
            System.out.print(localRoot.element + " ");
        }
    }
}

class Node {

    protected Student element;
    protected Node left;
    protected Node right;

    public Node(Student st) {
        element = st;
    }
}

【问题讨论】:

  • 您能解释一下n.element.returnList().contains(course) 的作用吗?据我所知,n.element 应该是Student 但它似乎没有方法returnList()。有什么我想念的吗?
  • n.element 应该是 Student,它应该是 getCourseList() 而不是返回列表,忘记编辑了。 if 条件应该检查​​当前节点的学生,以及他们是否包含正在检查的链接列表中的课程,并打印该课程中的所有学生。

标签: java linked-list binary-search-tree


【解决方案1】:

问题是您正在尝试查看 Course 类型的 LinkedList 是否包含字符串。 LinkedList 的 contains 方法将 Object 作为其参数类型,这就是您没有遇到编译问题的原因。

下面的代码 sn-p 永远不会为真,因为课程永远不会等于字符串。我在这里提到相等是因为 LinkedList contains 方法在内部检查您传入的对象与它包含的对象的相等性。

if(n.element.returnList().contains(course)) {
    System.out.print(n.element.getId() + " ");
}

使用地图的可能解决方案

在 Student 类中将课程更改为 Map,然后更改 IF 语句以检查 Map 是否包含基于课程名称的元素。如果地图包含一个对象,那么学生确实参加了这门课程。

class Student implements Comparable<Student> {

    String id;
    String firstName;
    String lastName;
    Map<String, Course> courses = new HashMap<>();

    Student(String id, String fName, String lName) {
        this.id = id;
        this.firstName = fName;
        this.lastName = lName;
    }

    public String getName() {
        return lastName;
    }

    public void setName(String lName) {
        this.lastName = lName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int compareTo(Student other) {
        return this.getId().compareTo(other.getId());
    }

    public void addCourse(Course course) {
        courses.put(course.getId(), course);
    }

    public Map<String, Course> getCourses() {
        return courses;
    }
}

IF 语句

if(n.element.getCourses().get(course) != null) {
    System.out.print(n.element.getId() + " ");
}

使用列表的可能解决方案

向 Student 类添加新方法。

 public boolean takesCourse(String courseName){
        for(Course course : courses){
            if(courseName.equals(course.getId)) {
                return true;
            }
        }

        return false;
    }

IF 语句

if(n.element.takesCourse(course)) {
    System.out.print(n.element.getId() + " ");
}

【讨论】:

  • 那么我该如何实现这个方法来检查当前节点的链表,并检查它是否包含正在搜索的课程?
  • 我已更新我的答案以显示可能的解决方案。我知道这是给你的家庭作业,所以我真的建议你阅读一下为什么该解决方案适用于地图
  • 是的,我不认为我可以使用地图,他在作业中严格规定,课程应该只使用 LinkedList 或 ArrayList。
  • 如果您严格需要使用 List,则向 Student 类添加一个方法,该方法将课程名称作为输入参数并返回一个布尔值。该方法应该遍历列表中的所有课程,如果输入课程等于课程 ID,则返回 true,如果没有课程 ID 与所需课程名称匹配,则返回 false。然后,您的 IF 语句将类似于 n.element.takesCourse(course)
  • @Devin .. 我添加了一个使用列表的解决方案示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2014-07-29
  • 2020-06-15
  • 2015-08-13
  • 2016-10-10
相关资源
最近更新 更多