2016-06-21 97 views
-2

我正在處理插入方法,我的方法是通過列表並插入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

如果你想添加一個節點在中間, - 首先,你必須要找到索引元素 - 點新元素的旁邊,搜索元素的下一個 - 點搜索元素的下一個新的元素

012。
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. 
}