链表中的实例变量

Instance variable in linked list

我写了一个关于病人的程序。我有自己的链表集合class。 我本可以使用 Java 的链表,但我的程序的想法是练习并更多地了解链表的工作原理。

这是我的程序的代码片段。

class PatientList {
 private PatientNode head;
 private int lastArrival;
 private int size;

 public PatientList() {
  head = null;
  lastArrival = 0;
  size = 0;
 }

 public void add(String name, int severity) {
  //PatientNode previous;
  Patient patient;

  lastArrival++;
  patient = new Patient(name, lastArrival, severity);

  head = new PatientNode(patient, head);
  size++;
 }

现在,我的问题是 size 实例变量。我似乎无论如何都得到 0。但是,当我尝试在 print 方法中计算 size 时,我得到了正确的 size 值。这是我的 print 方法代码:

public void print() {
 PatientNode current;
 //int size = 0;

 current = head;
 while (current != null) {
  System.out.println(current.data);
  //size++;
  current = current.next;
 }

 System.out.println("Size = " + size()); //size() method actually returns size.
 System.out.println("Last arrival = " + lastArrival);
}

谁能指出我在使用实例变量时做错了什么?我只是不明白为什么每次将某些内容添加到列表时我都在递增 size 时它会打印 0

编辑

大小方法就在这里,方便大家帮我解决问题

public int size() {
 return size;
}

编辑 2

String[] names = { "Zelma", "Clayton", "Casper", "Ihor", "Edwina" };
int[] severities = { 1, 2, 3, 1, 3 };
PatientList list;

list = new PatientList();
testPatientList(list, names, severities, 0);
}

public static void testPatientList(PatientList list, String[] names, int[] severities, int pos) {
 PatientList copy;

 if (pos < names.length) {
  list.add(names[pos], severities[pos]);
  copy = list.clone();

  copy.print();
  System.out.println("Admitting: " + copy.nextAdmission());
  System.out.println();

  testPatientList(list, names, severities, pos + 1);
  testPatientList(copy, names, severities, pos + 1);
  }
 }
}

我能够解决它。问题出在我制作列表的深层副本上。我没有为那里的尺寸做任何事情。

public PatientList clone() {
 PatientList copy;
 PatientNode current;
 PatientNode copyCurrent;
 PatientNode newNode;

 copy = new PatientList();
 current = head;
 copyCurrent = null;
 while (current != null) {
  newNode = new PatientNode(current.data, null);
  if (copyCurrent == null) {
   copy.head = newNode;
  } else {
   // last node in copy points to the new node
     copyCurrent.next = newNode;
  }
 // move to the next node in both lists
  copyCurrent = newNode;
  current = current.next;
}
 copy.lastArrival = lastArrival;
 copy.size = size; // had to add this line

 return copy;
}