While I'm doing an exercise about the linked lists in c, It has a question to insert a new node in the middle of the list. I finished, but then I didn't understand why I had to start at 2.
For example, if I start I = 0
linked list = 1,2,3,4,5
The value I want to insert is 6 at position 2. So I expect my linked list will be = 1,6,2,3,4,5. But the actual output will be 1,2,3,6,4,5.
Here is my code.
void Inserting(Node* head)
{
int n;
int i;
Node* Cur_Node = head;
Display(Cur_Node);
Node* NewNode = (Node*)malloc(sizeof(Node));
NewNode->next == NULL;
printf("What value your want to add : ");
scanf("%d",&(NewNode->number));
if (Cur_Node == NULL && NewNode == NULL)
{
return 0;
}
printf("Where do you want to put : ");
scanf("%d",&n);
for(int i=2; i < n; i++)
{
if(Cur_Node->next != NULL) {
Cur_Node = Cur_Node->next;
}
}
NewNode->next = Cur_Node->next;
Cur_Node->next = NewNode;
}