PIC16F84A PIC16F84A - 1 month ago 8
C Question

C - Linked List Insertion

I've wanted to create 5 nodels and insert a new nodle between 3rd and 4th one. Here is the code.. When I run it, I do not get either error or output. What have I done wrong ? Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

typedef struct node{

int data;
struct node *next;

}node;


int main(void) {

struct node *root, *newElement, *temp;

// first node is created.
root = (node*)malloc(sizeof(node));
root->data = 11;

// to create 4 nodes more after the first one is created.
int i;
for (i=0; i <= 3; i++){

root->next = (node*)malloc(sizeof(node));
root = root->next;
root->data = (i * 10);

}

// new node to insert.
newElement = (node*)malloc(sizeof(node));
newElement-> data = 1;



temp = (node*)malloc(sizeof(node));

temp = root->next->next;

root->next -> next = newElement;

newElement->next = temp;


// print the values
int j;
for(j=0; j<=4; j++){
root = root->next;
printf("%d\n", root->data);
}


return 0;

}

Answer

You are modifying root when you are creating the nodes, you should create some kind of iterator that starts at root and gets modified instead so that you don't lose the initial position.

Try the following:

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int data;
    struct node *next;
}node;


int main(void) {
    struct node *root, *newElement, *temp, *iterator;

    // first node is created.
    root = (node*)malloc(sizeof(node));
    iterator = root;
    iterator->data = 11;

    // to create 4 nodes more after the first one is created.
    int i;
    for (i=0; i <= 3; i++){
       iterator->next = (node*)malloc(sizeof(node));
       iterator = iterator->next;
       iterator->data = (i * 10);
    }

    // new node to insert.
    newElement = (node*)malloc(sizeof(node));
    newElement-> data = 1;

    temp = (node*)malloc(sizeof(node));

    iterator = root;
    temp = iterator->next->next;

    iterator->next->next = newElement;

    newElement->next = temp;

    iterator = root;
    // print the values 
    int j;
    for(j=0; j<=4; j++){
        printf("%d\n", root->data);
        iterator = iterator->next;
    }

    return 0;
}
Comments