2010-05-02 17 views
3

我有一個整數鏈表。當我插入一個新節點時,我需要將它插入到最後,但是在oder ...即2,4,5,8,11,12,33,55,58,102等等。我不認爲我將它插入正確的位置。看看我做錯了什麼?鏈接列表。按順序插入整數

Node newNode = new Node(someInt); 
Node current = head; 

     for(int i=0; i<count; i++){ 
      if(current == tail && tail.data < someInt){ 
       tail.next = newNode; 
      } 
      if(current.data < someInt && current.next.data >= someInt){ 
       newNode.next = current.next; 
       current.next = newNode; 
      } 
     } 
+1

除非您想通過索引或重複檢索,否則我建議您使用'SortedSet '和'Node implements Comparable '。 – BalusC 2010-05-02 20:50:19

+0

@BalusC:我很確定這是一個自己寫的X硬件分配,基於user69514問題歷史和問題本身。我懷疑這意味着真正的答案已經出來,儘管SortedSet 可能就足夠了,因爲看起來這就是所有的數據節點。 – Carl 2010-05-03 01:22:33

回答

4

我認爲這可能是更接近你在找什麼。

Node newNode = new Node(someInt); 
Node current = head; 
//check head first 
if (current.data > newNode.data) { 
    newNode.next = head; 
    head = newNode; 
} 

//check body 
else { 
    while(true){ 
    if(current == tail){ 
     current.next = newNode; 
     tail = newNode; 
     break; 
    } 
    if(current.data < someInt && current.next.data >= someInt){ 
     newNode.next = current.next; 
     current.next = newNode; 
     break; 
    } 
    current = current.next; 
    } 
} 
+0

這看起來更好,但它進入一個無限循環 – user69514 2010-05-02 21:11:28

+0

哎呀,忘了更新循環結束時的當前引用 – 2010-05-02 23:46:32

2

你永遠不會在列表中前進。你需要設置一個東西:

current = current.next 

您還可以添加一個break語句,因爲你正在與循環中完成這一點,你所插入的節點之後。

1

它看起來並不像你更新current ...嘗試在你的循環將是這樣的:

current = current.next; 
0

看起來你錯過了這種情況,當新的元素比所有現有的元素更小。