我必須編寫一個程序,按順序插入字符串,例如當我插入狗和貓,不管我插入它們的順序,它應該返回貓,狗。 截至目前,當我這樣做,它不插入順序,它插入就像正常。我很確定我的方法是切換頭部和當前的效果,因爲更早,它會翻轉我的輸入,無論它是否應該如此。如果它應該是貓狗,它會返回狗貓。無論出於何種原因,它都會出現在我的if語句中,它幾乎就像它跳過它。任何提示將非常感謝。有序插入到鏈接列表
public void insert(String s){
head= new node(s,head);
node current=head.getNext();
if(current == null){
current=head;
while(current.getNext() != null){
if(current.getData().compareTo(s)>0){
current.setNext(head);
head.setNext(current.getNext().getNext());
head=current;
current=head;
}
current= current.getNext();
}
}else{
while(current.getNext() != null){
if(current.getData().compareTo(s)>0){
current.setNext(head);
head.setNext(current.getNext().getNext());
head=current;
current=head;
}
current=current.getNext();
}
}
}
我可以,但老實說,這是一個重要任務,我們不允許。 – Haukka