Insert a node at a specific position in a linked list
To insert a node at position n:
- If
n == 1, perform a head insertion. - Otherwise, traverse the list to find the node at position
n-1. - Set the new node's
nextpointer to the currentn-th node (temp2->next). - Set the
n-1-th node'snextpointer to the new node.
void Insert(int date, int n)
{
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
temp1->date = date;
temp1->next = NULL;
if (n == 1) {
temp1->next = head;
head = temp1;
return;
}
struct Node* temp2 = head;
for (int i = 0; i < n - 2; i++) {
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}