Reputation: 19
I'm trying to implement function in linked list which will add a new note. That new node is a sum of a previous and next node.
Here is my code, but i don't know where is mistake.
void change(Node *head){
Node *p = head;
Node *temp = new Node;
temp->next = NULL;
while(p != NULL){
temp->data = p->data + p->next->data;
temp->next = p->next;
p->next = temp;
p = p->next;
}
}
Upvotes: 0
Views: 40
Reputation: 238411
If head
is null, then this function allocates a new Node
, but nothing points to the new node, so it will be leaked.
If head
isn't null, but is the last (i.e. the only) node of the list, then p->next->data
indirects through the null pointer, and the behaviour of the program is undefined.
Otherwise, in the first iteration, p->next = temp; p = p->next;
makes p
be the same as temp
, and in the second iteration p->next = temp;
makes the node point to itself, and the loop will never terminate.
Upvotes: 2
Reputation: 1065
If I have understood the problem correctly after reviewing the code, the changes made do not persist after the function call.
void change(Node *head ){
to
void change(Node *& head ){
Pls try this.
Edit:-
There are other problems in the code as pointed out by others like
1. Dereferencing a null pointer
2. Invalid memory access.
Upvotes: 0