我在特定位置插入节点时遇到黑客等级问题。我在这种情况下使用java,但我一直收到错误。而且我不知道如何解决它。我感谢您的帮助。这是我的解决方案:
/*`enter code here`
Insert Node at a given position in a linked list
head can be NULL
First element in the linked list is at position 0
Node is defined as
class Node {
int data;
Node next;
}*/
Node InsertNth(Node head, int data, int position) {
`enter code here`// This is a "method-only" submission.
// You only need to complete this method.
if(head == null){
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
return head;
}
if(position == 1){
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
return head;
}
// we need to go to n - 1
int counter = 0;
Node currNode = head;
Node prevNode = null;
while(counter != position -1 && currNode.next != null){
prevNode = currNode;
currNode = currNode.next;
counter++;
}
Node nNode = new Node();
nNode.data = data;
prevNode.next = nNode;
nNode.next = currNode;
return head;
/* another solution */
}
Result:
Exception in thread "main" java.lang.NullPointerException
at Node.InsertNth(Solution.java:54)
at Solution.main(Solution.java:89)
答案 0 :(得分:1)
在您给出的代码片段中,您在评论中提到第一个元素位于位置0.因此,如果插入发生在位置0,则head将发生变化。因此你做的条件
if(position == 1){
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
return head;
}
哟应该实际检查位置== 0.而你所说的输出中的不间断重复只是因为这个。例如,如果链接列表10-> 20,我希望在位置0插入30,然后我们按你的代码进行,然后我们不会将循环输入为0(计数器)!= -1(位置-1)所以我们prevNode和currNode现在都指向10和
Node nNode = new Node();
nNode.data = data;
prevNode.next = nNode; // you made 10 point to 30
nNode.next = currNode; // here you made 30 point to 10 so **loop** here
答案 1 :(得分:0)
就我所发送的信息而言,如果流不进入“while”循环,则会发生NullPointerException,因此“prevNode”将保持为null。然后,您将在“prevNode.next = nNode”行中获得异常。
如果您调试代码,将很容易获得。