【发布时间】:2015-10-20 20:08:34
【问题描述】:
Node InsertNth(Node head, int data, int position) {
Node start,curr,temp;
start=head;
curr=start;
if(start==null)
{
temp=new Node();
temp.data=data;
temp.next=null;
return head;
}
else if(position==0)
{
temp=new Node();
temp.data=data;
temp.next=start;
return head;
}
else
{
for(int i=0;i<position;i++)
{
System.out.println("i:"+i);
curr=start;
start=start.next;
}
temp=new Node();
temp.data=data;
curr.next=temp;
temp.next=start;
return head;
}
}
在上面的代码中,我在 for 循环中打印了“i”的值。 在控制台中,我得到的输出为
i:0
i:0
i:1
i:0
i:1
i:2
i:3
还有
Exception in thread "main" java.lang.NullPointerException
at Node.InsertNth(Solution.java:49)
at Solution.main(Solution.java:88)
为什么“i”没有正确递增?如果它运行良好,那么我可以在中间执行插入。
【问题讨论】:
-
你需要检查位置是否
-
好的!我将保持 start!=null 条件。但是,我一直得到相同的“i”值。为什么 i 值没有正确增加。
-
你作为位置传递了什么值?
-
你的第 49 行是什么?
-
这就是我没有得到的。我在 Hackerrank 网站上这样做。该函数将 positon 作为整数参数。这就是他提到的。
标签: java data-structures linked-list insertion