2013-09-27 23 views
0

奇數位置因此,例如,奇數如果原來的列表x3 5 6 8 9 2,新的鏈表h3 6 9建立一個新的鏈表,從原來的鏈表X的Java中

所以我想我的方法是工作和令人敬畏,但是當原始列表有超過3個元素時,我的列表奇數似乎沒有鏈接到下一個節點,當奇數列表超過3個元素。

我相信問題是在我的for循環時,我奇怪的列表的條件不是空的。 所以如果你們可以讓我知道我需要做什麼,我會很感激! 由於我是新來的,它不會讓我補充我的方法的打印屏幕,這裏是最好的下一件事:

public static Node oddPosition(iNode x){ 
    int count = 1; 
    iNode oddList = null; 
    for(Node temp = h; temp != null; temp = temp.next){ 
     if(count % 2 != 0){//<-----declares whether the position is odd or not 
      //if oddList is empty 
      if(oddList == null){ 
       oddList = new Node(temp.item); 
       oddList.next = null; 
      } 
      //if oddList is not empty 
      oddList.next = new Node(temp.item);//<----here is where I believe the problem is for some reason my linked list isnt linking together 
      oddList.next.next = null; 
     } 
     count++; 
    } 
    System.out.print("Odd list : "); 
    print(oddList); 
    return oddList; 
} 

輸出:

Original list : 3 5 6 8 9 2 
What is should display : 3 6 9 
What I am getting : 3 9 
+3

歡迎堆棧溢出!要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後如果有必要的話,你應該構建一個[最小測試用例](http://sscce.org)。) –

+0

如果我可以顯示輸出的圖片但是非常感謝我給我的問題添加更多 –

回答

0

你不斷加入新的元素,oddList.next 。 ou永遠不要改變oddList的值,所以這樣你的結果只有第一個元素和最後一個元素。某處必須指定oddList = oddList.next才能將新值添加到列表的末尾。而且您可能還想將第一個節點保存在單獨的值中,例如startOfList

那麼結果可能是這樣的:

public static Node oddPosition(iNode x){ 
int count = 1; 
iNode oddList = null; 
iNode startOfList = null; 
for(Node temp = h; temp != null; temp = temp.next){ 
    if(count % 2 != 0){//<-----declares whether the position is odd or not 
     //if oddList is empty 
     if(oddList == null){ 
      oddList = new Node(temp.item); 
      startOfList = oddList; 
      oddList.next = null; 
     } 
     //if oddList is not empty 
     oddList.next = new Node(temp.item); 
     oddList.next.next = null; 
     oddList = oddList.next; 
     } 
    count++; 
    } 
    System.out.print("Odd list : "); 
    print(startOfList); 
    return startOfList; 
} 
+0

非常感謝你ghaxx我知道那是我剛剛做的事情!你的救命啊! –