2015-11-05 107 views
0

我必須編寫一個程序,按順序插入字符串,例如當我插入狗和貓,不管我插入它們的順序,它應該返回貓,狗。 截至目前,當我這樣做,它不插入順序,它插入就像正常。我很確定我的方法是切換頭部和當前的效果,因爲更早,它會翻轉我的輸入,無論它是否應該如此。如果它應該是貓狗,它會返回狗貓。無論出於何種原因,它都會出現在我的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(); 
     } 
    } 
} 

回答

0

您可以按使用java.util.Collections防爆列表:

Collections.sort(your_list); 
+0

我可以,但老實說,這是一個重要任務,我們不允許。 – Haukka

0

有與您的代碼和邏輯的幾個問題。我會給提示固定下面你叫插入你的列表(我相信你的類的字段)創建一個新的head

  1. 每次。這不是鏈表列表的工作方式。您應該只創建一個新的headheadnull(空單)

  2. 你是新創建的head後設置current到下一個節點。因此它將具有分配給它的構造函數node的任何值。如果它指定了默認值null,那麼您將永遠不會進入if語句的else部分。

  3. 根據以上你將不可避免地在第一時間拿到你來自哪裏,null重新分配currenthead if語句。然後,你基本上是比較同一個節點(頭)的數據(字符串),你永遠不會進入下一個如果。

所以基本上你寫的功能等同於這個(嘗試一下)

public void insert(String s) { 
    head = new node(s, head); 
    node current = head.getNext(); 
} 

這可能不是你的原意。開始更改代碼時,只需創建head,當它爲空時,然後在此之後返回(如果列表只有一個元素不需要交換)。然後在頭部插入新節點並在需要時進行交換。

+0

關於當前應該怎麼辦?我對這一部分有點困惑。 – Haukka