how would i go about creating a function that will allow me to insert a new node at any index within a linked list? here\'s the struct:
struct node {
int
As you can see in the image below, you need to insert the node between two nodes.
The other 3 cases are
Maintain a count and loop through all the elements in the list. This count will help you keep track of the index.
Once you reach the node, where you have to insert the new node
Full Source Code available here
you have to deal with one special situation when index == 0, the headRef will need to be updated. or if index is greater than the number of elements in the list. The insert will fail. Otherwise check out the example code below.
int insertN(struct node** headRef, int index, int data) {
/* invalid headRef */
if (!headRef) {
return 0;
}
/* insert node at index */
int i;
struct node* new = (struct node *)malloc(sizeof(*node));
struct node *scan = *headRef;
new->data = data;
new->next = 0;
/* new head of list */
if (scan == NULL && index == 0) {
/* new head node */
new->next = *headRef;
*headRef = new;
return 0;
}
/* while not at end of list and not at index */
for (i = 0; scan != NULL && i <= index; i++) {
if (i == index) {
/* move what was here to next node and put in new node */
new->next = scan->next;
scan->next = new;
} else {
/* advance to next entry in list */
scan = scan->next;
}
}
/* scan == NULL indicates reached end of list before index */
return (scan != NULL);
}