有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将节点作为参数传递

我有一个自定义的链表,其中包含类Student的节点对象。有两种递归方法称为countNodesRec(节点列表)&;worstStudentRec(节点列表),两者都需要节点对象作为参数

清单1。最坏的研究中心(???)

清单1。countNodesRec(??)

我已经尝试过的参数给了我错误

  • 清单1。名单
  • 清单1

不知道该放什么,请帮忙

测试班

public class TestList {    
  public static void main(String[] args) {
    Student s1 = new Student("Adams", 3.9, 26);
    Student s2 = new Student("Lewis", 2.1, 29);
    Student s3 = new Student("Lopez", 4.0, 53);
    Student s4 = new Student("Smith", 3.2, 22);
    Student s5 = new Student("Zeeler", 3.6, 38);
    LinkedList list1 = new LinkedList();
    LinkedList list2 = new LinkedList();
    LinkedList list3 = new LinkedList();

    //1
    list1.addFront(s1);
    list1.addFront(s2);
    list1.addFront(s3);
    list1.addFront(s4);
    list1.addFront(s5);
    list1.printLinkedList();
    System.out.println("Worst Student" + list1.worstStudentRec());
    System.out.println("Number of Students" + list1.countNodesRec());

  }        
}

学生班

public class Student
{
  private String lastName;
  private double gpa;
  private int age;
  public Student(String lastName, double gpa, int age)
  {
    this.lastName = lastName;
    this.gpa = gpa;
    this.age = age;    
  }
  public int compareTo(Student s)
  {
    if (gpa < s.gpa)
    {
        return -1;
    }
    else if (gpa > s.gpa)
    {
        return 1;
    }
    else
    {
        return 0;
    }
  }
  public String toString()
  {
      return lastName + "\t" + gpa + "\t" + age;
  }
  public double getGpa()
  {
      return gpa;
  }
}

链表类

public class LinkedList 
{
  private class Node
  {
    public Student data;
    public Node next;
    public Node(Student s)
    {
      data = s;
      next = null;      
    }      
  }
  private Node list;
  public LinkedList()
  {
    list = null;
  }
  public Student bestStudent()
  {
    Student bestStudent, bstStu;
    Node current;
    if (list == null)
    {
      return bestStudent = null;
    }
    else
    {
      current = list;
      bstStu = new Student("", 0.00, 0);
      while (current != null)
      {
        if (bstStu.getGpa() <= current.data.getGpa())
        {
          bstStu = current.data;
        }
        current = current.next;
      }
      bestStudent = bstStu;
    }
    return bestStudent;
  }
  public int countNodesRec(Node list)
  {
    if(list == null)
    {
      return 0;
    }
    else
    {
      return 1 + countNodesRec(list.next);
    }
  }
  public Student worstStudentRec(Node list)
  {
    if (list == null)
    {
      return null;
    }
    else if (list.next == null)
    {
        return list.data;
    }
    Student worstStudent = worstStudentRec(list.next);
    return (list.data.compareTo(worstStudent) <= 0) ? list.data : worstStudent;
  }

}

共 (1) 个答案

  1. # 1 楼答案

    您可以在链表类中创建getList方法,然后在main中调用该方法:

    list1.worstStudentRec(list1.getList ())
    
    list1.countNodesRec(list1.getList ())