如何将节点作为参数传递

时间:2017-04-10 23:25:06

标签: java recursion linked-list parameter-passing nodes

我有一个自定义链表,其中包含Student类的节点对象。有两种递归方法叫做countNodesRec(Node list)& worstStudentRec(Node List),它们都需要节点对象作为参数。

list1.worstStudentRec(?????)

list1.countNodesRec(????)

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

  • list1.list
  • list1的

不确定放在那里,请帮助!

测试类

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 个答案:

答案 0 :(得分:0)

您可以在Linked List类中创建一个getList方法,然后在main中调用该方法:

list1.worstStudentRec(list1.getList ())

list1.countNodesRec(list1.getList ())