繁体   English   中英

链表添加方法无法正常工作

[英]Linked list add method not working as expected

因此,我正在尝试解决一个涉及将对象添加到链接列表的问题。 从早上开始我就一直在解决这个问题,到目前为止我还没有确切的输出。

我的程序基本上是根据severityarrival两个标准将患者添加到链表中。 我想使用severity从最高到最低添加患者。 如果它们确实具有相同的严重性,那么我想根据到达的升序存储它们。 例如

患者1,到达2,严重性3

患者2,到达3,严重性3

或者,如果它们的严重性不同,则如下所示:

患者1,到达2,严重度2

患者2,到达1,严重性1

简而言之, severity必须按降序排列, 如果严重性相同,则根据arrival顺序将它们按升序存储。

到目前为止,我尝试过的是此方法,该方法在patient类中:

public boolean compareSeverity(Patient other) {
 boolean result = false;
 if(other.severity > severity) {
  result = true;
 } else if(other.severity == severity) {
    if(other.arrival > arrival) {
     result = true;
    } else {
      result = false;
    }
  } else {
    result = false;
  }
  return result;
 }

这就是我为linked list类编码add方法的方式。

public void add(String name, int severity) {
 lastArrival++;
 Patient patient = new Patient(name, lastArrival, severity);
 PatientNode current, previous;
 current = head;
 previous = null;
 if(head == null) {
  head = current = new PatientNode(patient, head);
  size++;
 } else {
   while(current!=null) {
    //previous = current;
    if(current.data.compareSeverity(patient)) {
     PatientNode n = new PatientNode(patient,current);
     size++;
     if(previous!=null) {
      previous.next = n;
      }
      return;
     }
     previous = current;
     current = current.next;
    }
  }
 }

但是,当我尝试运行我的程序时,它仅显示一名患者。

从早上开始,我就一直在修补自己的方法,这是到目前为止我所得到的。 也许我需要重新审视,因为现在我无法解决这个问题。 任何帮助将不胜感激。 我得到的输出

编辑2

该列表已完全打印出来,但没有执行标准,如果严重性相同,则以升序存储患者。

新输出

您将指针从前一个设置为n,但从未将指针从n设置为下一个。 您仅在链接列表中创建所需的两个链接之一。

if(current.data.compareSeverity(patient)) {
    PatientNode nextHolder = current.next;
    PatientNode n = new PatientNode(patient,current);
    size++;
    n.next = current;   //this line forgotten??
    if(previous==null) {
        head = n;
    }
    else {
        previous.next = n;
    }
    return;
}


previous = current;
current = current.next;

您还需要处理新专利在列表中排在第一位的情况,并且head变量需要更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM