例如,如果原始列表x
为3 5 6 8 9 2
,则新的链接列表h
将为3 6 9
所以我认为我的方法正常工作并且非常棒但是当原始列表有超过3个元素时,当list odd有超过3个元素时,我的list奇怪似乎没有链接到下一个节点。
我相信当我的奇数列表的条件不为空时,问题出在我的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
答案 0 :(得分: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;
}