2016-11-25 151 views
0

所以我试图解决一个问题,涉及添加对象到链接列表。自上午以来,我一直在讨论这个问题,至今我还没有得到确切的结果。链接列表添加方法不按预期工作

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

这也是我如何编码的我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++; 
    if(previous!=null) { 
     previous.next = n; 
     } 
     return; 
    } 
    previous = current; 
    current = current.next; 
    } 
    } 
} 

但是,当我尝试运行我的程序时,它只显示一个病人。

我从早上一直在修补我的方法,这是迄今为止我所得到的。也许我需要一套新的眼睛,因为现在我无法解决这个问题。任何帮助将不胜感激。 The output that i am getting

编辑2

列表被完全打印出来,但它不执行标准,如果严重程度是一样的,然后存储患者按升序排列。

New Output

回答

0

您从以前的指针设置为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; 

您还需要处理新专利在列表中首先出现,并且头部变量需要更新的情况。

+0

我是不是通过'if(head == null)'声明来处理第一个病人? – Mooe

+0

我刚刚运行该程序,但仍显示只有一名患者。看起来它正在失去节点。 – Mooe

+0

我刚刚在新患者列表中的第一个病例中进行了适当的更正。在这种情况下,您需要将头部变量指向新记录。如果你的测试不是这样的话,那么你可能最终永远不会更新头部,除非你输入第一个,否则绝不会看到任何东西。 – AgilePro