The program should insert a node that is a sum of next 2 nodes

stdin: 2->7->4->9;

stdout: 2->11->7->13->4->9;

The program returns a segmentation fault,I'm not sure what seems to be the problem.

void insert(Node * list){

   if (list==NULL) {

   return;

    }

for(; (list->next->next)!=NULL ; list=list->next){

 Node* new=(Node*)malloc(sizeof(Node));

  if(new == NULL)

   return;

else {

 new->data= (( list->next->next )->data )+( (list->next)-> data );

  new->next = list->next;

   list->next = new;

list = list->next->next ;

     }
   }
 }

Recommended Answers

All 2 Replies

Inserting a node that is the sum of the next two nodes creates an infinite process. Consider:

Original: 1 -> 2 -> 3 -> 4
Iteration 1:
          1 -> 2 -> 3 -> 4
          ^ (add 2 + 3, insert node)
          1 -> 5 -> 2 -> 3 -> 4
               ^ (increment pointer)
Iteration 2:
          1 -> 5 -> 2 -> 3 -> 4
               ^ (add 2 + 3, insert node)
          1 -> 5 -> 5 -> 2 -> 3 -> 4
                    ^ (increment pointer)

You can see that you will never get to the end of the list if you continue to grow it.

As for why you get your issues, you are not checking all the pointers you are dereferencing. Consider:

if (list==NULL) {
   return;
}

for(; (list->next->next)!=NULL ; list=list->next) {
   // ...
}

What happens when list->next is NULL?

Remove the statement 25 and in line 9 in for loop change

list=list->next

with

list=list->next->next
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.