我编写了将患者添加到链接列表的程序。现在,我能够获得输出。我调整了代码,以便根据严重性从高到低插入患者,如果严重性相同,则根据时间插入患者。我的患者类别具有三个属性名称:到达和严重性。
编辑3
我在compareSeverity
类中添加了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;
}
这是
PatientNode
代码段。class PatientNode {
public Patient data;
public PatientNode next;
public PatientNode(Patient data, PatientNode next) {
this.data = data;
this.next = next;
}
}
这是
add
类中的linked list
方法。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++;
n.next = current;
if(previous==null) {
head = n;
} else {
previous.next = n;
}
return;
}
previous = current;
current = current.next;
}
}
}
我现在得到的输出是当问题似乎与相同的
severity
患者有关时的输出。我希望我的输出看起来像这样:
患者1,到达2,严重性3
患者2,到达3,严重性3
或者,如果它们的严重性不同,则如下所示:
患者1,到达2,严重度2
患者2,到达1,严重性1
简而言之,
severity
必须按降序排列,如果严重性相同,则根据arrival
将它们按升序存储。我要根据严重程度存储患者的任何想法/指标或伪代码都非常好,谢谢。
最佳答案
在代码中使用compareSeverity更新之后:
条件if(other.arrival > arrival) {
应该为if(other.arrival < arrival) {
,并且if
-子句可以在compareSeverity
方法中简化,因为您只需要指定何时需要在true
上设置值,而不是初始化的false
您的变量。
public boolean compareSeverity(Patient other) {
boolean result = false;
if((other.severity > severity) || (other.severity == severity && other.arrival < arrival)) {
result = true;
}
return result;
}
因为它只是设置一个布尔值,所以您甚至可以让它变成:
public boolean compareSeverity(Patient other) {
return (other.severity > severity) || (other.severity == severity && other.arrival < arrival);
}
您在while循环之后忘记了
add
方法中的if条件。如果current
变为null
怎么办?当您无法在链接列表中插入患者时,就会发生这种情况,因此您必须将其作为最后一个元素放在后面。public void add(String name, int severity) {
lastArrival++;
Patient patient = new Patient(name, lastArrival, severity);
if(head == null) {
head = new PatientNode(patient, head);
size++;
} else {
PatientNode current, previous;
current = head;
previous = null;
while(current!=null) {
if(current.data.compareSeverity(patient)) {
PatientNode n = new PatientNode(patient,current);
size++;
//n.next = current; // overkill
if(previous==null) {
head = n;
} else {
previous.next = n;
}
return;
}
previous = current;
current = current.next;
}
if(current == null){
previous.next = new PatientNode(patient, null);
size++;
}
}
}
我可以为您提供更新代码的a working example