从原始链表x';构建新的奇数链表;java中的奇数位置
因此,例如,如果原始列表从原始链表x';构建新的奇数链表;java中的奇数位置,java,linked-list,Java,Linked List,因此,例如,如果原始列表x是3 5 6 8 9 2,则新的链表h将是3 6 9 所以我认为我的方法是有效的,非常棒,但是当原始列表有3个以上的元素时,当列表奇数有3个以上的元素时,我的列表奇数似乎没有链接到下一个节点 我相信当我的奇数列表的条件不是空的时候,问题就在我的for循环中。 所以如果你们能让我知道我需要做什么,我会非常感激! 因为我是新来的,所以我不会只添加我的方法的打印屏幕,所以下面是最好的: public static Node oddPosition( iNode x){
x
是3 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;
}
您不断向
oddList.next添加新元素。您永远不会更改oddList
的值,因此这样您的结果只有第一个元素和最后一个元素。您必须在某个地方分配oddList=oddList。下一步
,以便能够在列表末尾添加新值。您可能还希望将第一个节点保留在单独的值中,例如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;
}
公共静态节点oddPosition(iNode x){
整数计数=1;
iNode oddList=null;
iNode startOfList=null;
对于(节点温度=h;温度!=null;温度=temp.next){
如果(计数%2!=0){//欢迎使用堆栈溢出!要求人们发现代码中的错误不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与预期发生的情况进行比较。一旦这两种情况出现分歧,您就发现了问题。(如果有必要的话,你应该构建一个。)很抱歉,如果我能展示一张输出的图片,事情会简单得多,但是谢谢你,我会在我的问题中添加更多的内容。谢谢你,我知道这就是我一直在做的问题!你是一个救生员
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;
}