2016-06-21 10 views
-2

私はinsertメソッドを使っています。私のメソッドはリストを通ってitem.thereforeを挿入しています。もしifとelseを使用した場合:最初に追加します。途中であれば、私はそれが最後であれば私を助けることができますか?リンクされたリストとノードを挿入する

public Node helpinsert(Node n) 
{ 
    Node current = first; 
    Node pre=null; 

    while(current!=null && current.next!=null) 
    { 
     if(current.compareTo(n)<0){ 
      break; 
     } else { 
      pre=current; 
      current=current.next; 
     } 
    } 

    //if current is on first 
    if(current==first){ 
     n.next=current; 
     first=n; 
    } 
} 

答えて

0

中にノードを追加する場合は、 - 最初にインデックス要素を見つけなければなりません - 検索された要素の次の要素の次の要素を指します - 検索された要素の新しい要素を指します

if(current != first && current != last){ //searched element is current 
    n.next = current.next; //Point new element's next to searched element's next. 
    current.next = n; //Point the searched element's next to new element. 
} 

最後にノードを追加する場合は、 - まずインデックス要素を見つける必要があります。 - 新しい要素がnullの横にあることを示します。 - 検索された要素を新しい要素の隣にポイントします。

if(current == last){ //searched element is current 
     n.next = null; //Point new element's next to null. 
     current.next = n; //Point the searched element's next to new element. 
} 
関連する問題