链表和对象问题

时间:2015-10-06 18:33:45

标签: java data-structures

我正在尝试使用对象实现链接列表。编译代码时出现错误信息:

Person.java:49: error: constructor Node in class Node cannot be applied to given types;
      Node newNode = new Node(last, first, age);

有人可以帮我一把吗?为什么会这样?谢谢。 这是代码:

    class Person{

private String lastName;
private String firstName;
private int age;

   public Person(String last, String first, int a){
      lastName=last;
      firstName=first;
      age=a;
   } 

   public void displayPerson(){
      System.out.println("Last Name: "+lastName);
      System.out.println("First name"+firstName);
      System.out.println("Age: "+age);
   }

   public String getLast(){
      return lastName;                                                                                                             
   }
}

class Node
{
   public Person data; 
   public Node next; 

   public Node(Person d)
   {
      data = d; 
   }

}
class LinkList
{
   private Node first;

   public  LinkList()
   {
      first = null;
   }
   public boolean isEmpty()
   {
      return (first==null);
   }
   public void insertFirst(String last, String first, int age)
   {
      Node newNode = new Node(last, first, age);
      newNode.next = first;
      first = newNode;
   }
   public Node deleteFirst(String last, String first, int age)
   {
      Node temp = first;
      first = first.next;
      return temp;
   }
   public void displayList()
   {
      System.out.print("Linked List (first -->last): ");
      Node current = first;
      while(current != null)
      {
         current.displayPerson();
         current = current.next;
      }
      System.out.println(" ");
   }
}

3 个答案:

答案 0 :(得分:1)

该行

Node newNode = new Node(last, first, age);

不编译,因为Node类没有包含这些类型的三个参数的构造函数。看来你想要

Node newNode = new Node(new Person(last, first, age));

答案 1 :(得分:0)

Node newNode = new Node(last, first, age);

Node没有一个带3个参数的构造函数。

我假设您打算首先创建一个Person对象,然后将其传递给Node构造函数,例如new Node(new Person(last, first, age))

答案 2 :(得分:0)

我在您的代码中看到了一些其他错误,例如:

  • 在insertFirst方法上,您的String第一个参数隐藏了您的Node第一个属性。您应重命名参数以避免此
  • 在你的displayList方法上你有current.displayPerson(),我想你想要current.data.displayPerson()

希望这会有所帮助:) 阿尔贝托