Reputation: 37
so I want to add inbetween two nodes of a linked list a new node whose data field basically contains the sum of the the previous and the next node. I can't understand why once I enter the while loop I can't get out of it. Any suggestions? Thank you.
Here's my code:
void modify_list (node *head) {
nodo *it = head;
nodo *prev = NULL;
int n_prev = 0;
int n_next = 0;
int sum = 0;
it = it->next;
prev = it;
while (it->next != NULL) {
it->data = n_next;
prev->data = n_prev;
sum = n_next + n_prev;
node *new;
new = malloc(sizeof(node));
if (new == NULL) {
printf("Error.\n");
return;
}
memset(nuovo, 0, sizeof(node));
new->data = sum;
prev->next = new;
new->next = it;
sum = 0;
prev = it;
it = it->next;
}
}
Upvotes: 0
Views: 87
Reputation: 7687
May I first suggest breaking your code up in smaller parts
Have a function that inserts a new object
For a singly linked list, this should insert after:
void InsertAfter( Node* n, DATA data )
{
Node* newnode = malloc(sizeof(Node));
newnode->data = data;
newnode->next = n->next;
n->next = newnode;
}
Then you have a function to find the insert-point
It could be for example
Node* FindLastSmaller( Node* n, DATA data )
{
while(true)
{
if( ! n->next ) return n;
if( n->next->data > data ) return n;
n = n->next;
}
}
Then they become easy to combine:
void InsertSorted( Node* n, DATA data )
{
Node* inspos = FindLastSmaller(n,data);
InsertAfter(inspos,data);
}
You can avoid adding special-cases for empty list, if head
always
exists, and contains no data. (its a dummy node)
Upvotes: 0
Reputation: 206697
When you start the iteration, you are using:
it = it->next;
prev = it;
it
and prev
are pointing to the same node. A little while later, you are using:
prev->next = new;
which is the same as:
it->next = new;
That means it->next
points to the new node. That means, you never really go past the newly created nodes.
You can fix this by using:
prev = it;
it = it->next;
before the start of the while
loop.
I would make that more robust by using:
prev = it;
if ( it != NULL )
{
it = it->next;
}
At this time, it
could be NULL. Change the conditional in the while
statement to:
while (it != NULL) {
Upvotes: 1