Acetamide - 3 months ago 20

Java Question

I am currently working on a linked list that need to insert and delete data from the position that user input. However, I have met some error with insertion. I follow the code that I found online and I don't know where is the problem, the data that I enter did not insert to the linked list, everytime I display the linked list it shows me NULL even I do have insert some data in it.

Here is my code for insertion:

`public void addItemRequest(Node head, int item, int position)`

{

Node prevNode = head;

Node newNode = new Node(item,null);

if (head==null)

{

return;

}

if (position == 0)

{

newNode.next = head;

return;

}

int count = 0;

while (count < position -1 && head.next != null)

{

head = head.next;

count++;

}

Node currNode = head.next;

head.next = newNode;

head = head.next;

head.next = currNode;

return;

}

Here is my code for Node class:

`class Node{`

int num;

Node next;

Node()

{

num=0;

next=null;

}

Node(int num, Node next)

{

this.num=num;

this.next=next;

}

int getNum()

{

return num;

}

Node getNext()

{

return next;

}

void setNext(Node next)

{

this.next=next;

}

}

I hope someone could tell me what is the problem here, thanks.

Answer

**You have to make head as a global variable then only it will work**

Go easy with only one temp node that is new

```
public void addItemRequest(Node head, int item, int position)
{
Node prevNode = head;
Node newNode = new Node(item,null);
if (head==null)
{
head=newNode;
return;
}
if (position == 0)
{
newNode.next = head;
head = newNode;
return;
}
int count = 0;
while (count < position -1 && head.next != null)
{
prevNode = prevNode.next;
count++;
}
newNode.next = prevNode.next;
prevNode.next = newNode;
return;
}
```

Check now. I have corrected the answer. `head=newNode;`

has to added in `if (position == 0)`

If you really want to appreciate accept the answer and upvote it. So that someone like you can also find the solution easily.