0

因此,例如,如果原始列表x3 5 6 8 9 2,则新的链表h将是3 6 9

所以我认为我的方法有效并且很棒,但是当原始列表有超过 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
4

1 回答 1

0

你不断地向oddList.next. 你永远不会改变值,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;
}
于 2013-09-27T15:35:48.717 回答