0

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 ;

     }
   }
 }
3
Contributors
2
Replies
22
Views
3 Years
Discussion Span
Last Post by Akash_Soni
1

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?

0

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

list=list->next

with

list=list->next->next
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.