【问题标题】:Linked list add method not working as expected链表添加方法未按预期工作
【发布时间】:2016-11-25 23:14:26
【问题描述】:

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

我的程序基本上是根据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;
    }
  }
 }

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

我从早上开始就一直在修改我的方法,这就是我到目前为止所得到的。也许我需要一双新的眼睛,因为现在我无处可去解决这个问题。任何帮助将不胜感激。 The output that i am getting

编辑 2

该列表正在完全打印出来,但它没有执行如果严重程度相同则按升序存储患者的标准。

New Output

【问题讨论】:

    标签: java pointers linked-list nodes singly-linked-list


    【解决方案1】:

    您将指针从上一个设置为 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变量。

    【讨论】:

    • 我不是通过if(head==null) 声明处理第一个病人吗?
    • 我刚刚运行了程序,但它仍然只显示一名患者。似乎它正在丢失节点。
    • 我刚刚为新患者是列表中的第一个的情况添加了适当的更正。在这种情况下,您需要使 head 变量指向新记录。如果您的测试没有做到这一点,那么您最终可能永远不会更新头部,并且除了您放入的第一个之外什么都看不到。
    • 就输出而言,这很好,但是当患者的严重性相同按升序排列时,代码似乎没有存储患者。我添加了一个新的输出来显示我在说什么。
    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2020-10-04
    相关资源
    最近更新 更多