I have a few questions about this function which intends to delete all occurrence of a given integer in the list :
void deleteAllOcc (node**headRef,int d)
{
node*temp;
if (*headRef==NULL)
return;
while (*headRef)
{
if ((*headRef)->data==d)
{
temp=*headRef;
*headRef=(*headRef)->next;
free(temp);
}
else
{
headRef=&((*headRef)->next);
}
}
}
First why did we use **headRef instead of *head ?
Secondly, considering this :
if ((*headRef)->data==d)
{
temp=*headRef;
*headRef=(*headRef)->next;
free(temp);
}
Don't we need to update the links ?
And third, considering this :
else
{
headRef=&((*headRef)->next);
}
Why we didnt do *headRef=(*headRef)->next); here?
Thanks in advance
For starters the function can be written simpler
void deleteAllOcc( node **headRef, int d )
{
while ( *headRef != NULL )
{
if ( ( *headRef )->data == d )
{
node *temp = *headRef;
*headRef = ( *headRef )->next;
free( temp );
}
else
{
headRef = &( *headRef )->next;
}
}
}
That is the first check for the equality of the passed by reference the pointer to the head node is redundant.
First why did we use **headRef instead of *head?
It depends on how the function is defined. In the case of the function definition provided in your question the pointer to the head node is passed by reference that is through a pointer to the pointer head. In this case changing the pointed pointer head within the function you are changing the original function.
For example imagine that the list contains only one node and its data member data is equal to the specified value of the argument d.
in main
node *head = malloc( sizeof( mode ) );
head->data = 1;
head->next = NULL;
deleteAllOcc( &head, 1 );
//...
and within the function deleteAllOcc you have
if((*headRef)->data==d)
{
temp=*headRef;
*headRef=(*headRef)->next;
free(temp);
}
As *headRef yields the original pointer head in main then this statement
*headRef=(*headRef)->next;
changes the original pointer head in main bot a copy of the value of the pointer.
You could define the function in other way when the pointer to the head node is not passed by reference but passed by value. But in this case you need to return the possible new value for the pointer to the head node in main.
For example
node * deleteAllOcc( node *head, int d )
{
while ( head != NULL && head->data == d )
{
node *temp = head;
head = head->next;
free( temp );
}
if ( head != NULL )
{
for ( node *current = head; current->next != NULL; )
{
if ( current->next->data == d )
{
node *temp = current->next;
current->next = current->next->next;
free( temp );
}
else
{
current = current->next;
}
}
}
return head;
}
and in main the function should be called for example like
node *head = NULL;
//filling the list
head = deleteAllOcc( head, 1 );
As you can see the function definition when the pointer to the head node is passed by reference looks more simpler.
how are we updating the links between the nodes after deleting a node
You have a pointer to the data member next of the current node. The pointed node by the data member next of the current node contains the value equal to the value of the parameter d. So the next node must be deleted. It ,means that the data member next of the current node shall point to the node after the deleted node. That is you need to write
*headRef = ( *headRef )->next;
where headRef at the current moment points to the data member next of the current
node.
|node1| next | -> |node2| next | -> |node3| next |
| |
headRef node that must be deleted
So in the data member next pointed to by headRef you have to write the value of the data member next of the deleted node node2.
why we didnt do *headRef=(*headRef)->next); here?
In this code snippet
else
{
headRef=&((*headRef)->next);
}
you are reallocating the pointer headRef to point to the data member next of the next node. If you will write
*headRef = ( *headRef )->next;
then you will lose the node currently pointed to by the value stored in the expression *headRef that is in the currently pointed data member next will be changed rewriting the stored pointer.
First why did we use **headRef instead of *head?
When you send the adress of a linked list to a function, you create a pointer on the first element of this list. It allows you to iterate on the list etc. But if you want to manipulate the complete list (or edit it), you have to create a pointer on this list, (that means a double pointer on this list by sending the adress of the linked list
why we didnt do *headRef=(*headRef)->next); here?
Your method can work but I advise you to create a pointer to a temporary node *(node tmp) in order to assign the value to it and swap data with it. It's much more readable for everyone.
Related
I am currently working through C Programming A Modern Approach by K.N. King, and one of the exercise questions is:
The following function is supposed to insert a new node into its proper place in an ordered list, returning a pointer to the first node in the modified list. Unfortunately, the function doesn't word correctly in all cases. Explain what's wrong with it and show how to fix it. Assume that the node structure is the one defined in Section 17.5.
struct node
{
int value;
struct node next;
};
struct node *insert_into_ordered_list(struct node *list, struct node *new_node)
{
struct node *cur = list, *prev = NULL;
while (cur->value <= new_node->value) {
prev = cur;
cur = cur->next;
}
prev->next = new_node;
new_node->next = cur;
return list;
}
After trying to understand this for a while and struggling, I eventually came across another stackoverflow question where someone posted this as their answer.
I currently don't have enough reputation to ask about it on there, so I'm asking here to try to wrap my head around this.
struct node * insert_into_ordered_list( struct node *list, struct node *new_node )
{
struct node **pp = &list;
while ( *pp != NULL && !( new_node->value < ( *pp )->value ) )
{
pp = &( *pp )->next;
}
new_node->next = *pp;
*pp = new_node;
return list;
}
Could someone explain to me how the previous node, the one before the inserted new_node is being updated to point at the inserted new_node? I'm guessing the line *pp = new_node; has something to do with it, but I can't understand how. Thank you.
As you said, pp is a pointer to the pointer to the "current node in the position in the list" - this is sometimes called a "handler" in the literature. The name pp comes from "pointer to pointer".
* is the "dereference operator", specifically it means "the data at", so *pp means "the data at memory location pp," which in this case is the actual pointer to the current node.
When you use an assignment operator with a derefernce, you are saying set the data at memory location pp to new_node (that data happens to also be a pointer). Remember, new_node is a pointer to your new node's data. So when you run the line:
new_node->next = *pp;
you are setting the "next" entry in the data at new_node equal to the pointer to the "current" node. Then when you run the line:
*pp = new_node;
you are updating the pointer at location pp to point to the structured data in struct node format at new_node.
Sometimes when unwrapping all these pointers and dereferences in C, it helps me to make sure I understand the type of every expression and subexpression.
For example here are various expressions above, and their types, expressed as boolean operations in modern C using the typeof operator. Note that in a real program, at compile time these will be replaced with the value 1 ("truthy" in C) :)
typeof(new_node) == struct node *;
typeof(pp) == struct node **;
typeof(*pp) == struct node *;
typeof(*new_node) = struct node;
Note that since in C, the = operator causes memory to be copied to cause the left side of the expression to be equal to the right side in any future evaluations (commonly referred to as the lvalue and the rvalue of the expression). So in the parlance, After an = the lvalue could evaluate differently than before. The rvalue is used for calculating the new value of the lvalue, but itself remains unmodified after the assignment operation.
It is important to remember, anytime you use = you are blowing over any data in the lvalue. This is often confusing, as = is the ONLY operator in C that causes "side-effects" (Sometimes () is also considered an operator, of course function calls can also cause side-effects, as in this example using a pointer argument to the function and dereferencing it within the function body).
ALL other operators simply evaluate inside expressions (for example, *, &, + etc.), but when you use = it makes changes. For example, any given expression containing the lvalue or anything dependent on the lvalue might evaluate to a different value before and after an = operation. Because functions can have pointer arguments as in this example, function calls can also cause side effects.
You can also, more simply, think of * as an operator that "removes *'s" from types, and & as an operator that "adds *'s" to types - as above they are called the dereference and reference operator.
pp either initially points to the pointer head or due to the while loop to the data member next of some node
while ( *pp != NULL && !( new_node->value < ( *pp )->value ) )
{
pp = &( *pp )->next;
}
For example if pp points to head. If head is equal to NULL or new_node->value < head->value then these statements
new_node->next = *pp;
*pp = new_node;
in fact are equivalent to
new_node->next = head;
head = new_node
If pp points to the data member next of some node then these statements
new_node->next = *pp;
*pp = new_node;
change the value of the of the current data member next with the address of the new node
*pp = new_node;
and before this the data member next of the new node is set to the value stored in the data member next of the current node.
As for this function
struct node *insert_into_ordered_list(struct node *list, struct node *new_node)
{
struct node *cur = list, *prev = NULL;
while (cur->value <= new_node->value) {
prev = cur;
cur = cur->next;
}
prev->next = new_node;
new_node->next = cur;
return list;
}
then there is no check whether the pointer cur becomes (or initially is) equal to NULL. And secondly the pointer list is not changed when the new node is inserted before the node pointed to by list.
The function could be defined the following way
struct node *insert_into_ordered_list(struct node *list, struct node *new_node)
{
if ( list == NULL || new_node->value < list->value )
{
new_node->next = list;
list = new_node;
}
else
{
struct node *cur = list;
while ( cur->next != NULL && cur->next->value <= new_node->value)
{
cur = cur->next;
}
new_node->next = cur->next;
cur->next = new_node;
}
return list;
}
Before calling the free(); function if I don't assign NULL value to the link part of the node that I want to delete, what will be the problem ? I reviewed some codes of deleting nodes in other websites, but I found no assignment of NULL value to the link part. They just called the free(); function. Please reply to remove my confusion. Thank you.
struct node
{
int data;
struct node * next;
}
struct node * head = NULL; //This is the head node.
/* Here some other functions to create the list */
/* And head node is not going to be NULL here, after creating the list */
void deleteFirstNode()
{
struct node * temp = head;
head = temp->next;
temp->next = NULL; //my question is in this line, is this line necessary?
free(temp);
}
No, the line
temp->next = NULL;
is not necessary. Any data in the node pointed to by temp will become invalid as soon as free is called, so changing any values inside that node immediately before they become invalid will have no effect.
This function can invoke undefined behavior when will be called for an empty list due to these statements
struct node * temp = head;
head = temp->next;
because in this case head is equal to NULL.
The function frees the memory occupied by an object of the type struct node. So there is no sense to change the deleted object. This statement
temp->next = NULL; //my question is in this line, is this line necessary?
is redundant.
It is the same as before deleting the node to write
temp->data = INT_MAX;
This does not influence on the list.
The function can look like
void deleteFirstNode()
{
if ( head != NULL )
{
struct node *temp = head;
head = head->next;
free( temp );
}
}
Also it is a bad idea to define function that depend on global variables. In this case you will be unable for example to create more than one list in the program. It is better when the pointer to the head node is passed to the function deleteFirstNode by reference.
In this case the function can look like
void deleteFirstNode( struct node **head )
{
if ( head != NULL )
{
struct node *temp = *head;
*head = ( *head )->next;
free( temp );
}
}
And the function can be called like
deleteFirstNode( &head );
I'm using codeBlock and i'm trying to delete all the nodes with zero value
at first i deleted the head nodes until there is no zero value in head
like that
void exo6(Node* head)
{
Node* p=(Node*)malloc(sizeof(Node));
p=head;
head=p;
if(p->data==0)
{
while(p->data==0)
{
head=p->next;
free(p);
p=head;
}
}
head=p;
Then i continue to delete the next nodes like that
while(p!=null)
{
if(p->next->data==0)
{
Node* q=p->next;
free(p->next);
p->next=q->next;
}else
p=p->next;
}
printf("The NEw list is \n");
display(head);
}
but the code worked only on the head nodes
the result is like this
The simplest way is when the function accepts the pointer to the head node by reference.
Here you are.
void exo6( Node **head )
{
while ( *head != NULL )
{
if ( ( *head )->data == 0 )
{
Node *current = *head;
*head = ( *head )->next;
free( current );
}
else
{
head = &( *head )->next;
}
}
}
Call the function like
exo6( &head )l
As for your function implementation then it starts from a memory leak
void exo6(Node* head)
{
Node* p=(Node*)malloc(sizeof(Node));
p=head;
// ...
At first memory is allocated and its address is stored in the pointer p and then at once the pointer is reassigned. Also take into account that in general the function can be called when the pointer to the head node is equal to NULL.
Moreover the function accepts the pointer to the head node by value. So the function deals with a copy of the original pointer. Changing the copy does not influence on the original pointer.
I am new to programming. I just want to know why this doesn't work.
My understanding of pointers isn't clear, especially when using pointers across functions.
void append(struct Node** head_ref, float new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
struct Node *last = *head_ref; /* used in step 5*/
new_node->data = new_data;
new_node->next = NULL;
while (last != NULL)
last = last->next;
last = new_node;
return;
}
void append(struct Node** head_ref, float new_data)
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
In the first function the new data doesn't get included, I get only the original linked list.
But the second function works just fine. How does a double pointer work when inserting a new node in the beginning of the linked list? (I have seen answers regarding this question, but I am still confused)
In the first example, you move the pointer last until it points at a NULL location. Then, you set the pointer to new_node. However, at this point, last has no real association to your linked list. It is just a pointer to some memory. In the second example, the correct one, you iterate until you reach the tail of the linked list, where next of that node is NULL. Then, you set that next to new_node. There is now a new tail to the list, that is new_node.
Changing the local variable last does not change the value of the data member next of the previous (last) node.
To be more clear let's assume that the list is empty. Then you have to change the pointer referenced by this double pointer head_ref.
You declared a new pointer
struct Node *last = *head_ref;
The loop
while (last != NULL)
last = last->next;
is skipped because now already last is equal to NULL die to the initialization in the previous declaration. And then you changed this local variable last
last = new_node;
The original value of the pointer pointed by head_ref was not changed because last and *head_ref occupy different extents of memory. You changed the memory occupied by last but not changed the memory occupied by head_ref.
Also you should check whether a memory was successfully allocated.
The function can look the following way
int append( struct Node **head_ref, float new_data )
{
struct Node *new_node = malloc( sizeof( struct Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = new_data;
new_node->next = NULL;
while ( *head_ref != NULL ) head_ref = &( *head_ref )->next;
*head_ref = new_node;
}
return success;
}
As for this loop (I think you wanted just to show the loop not a whole function)
while (last->next != NULL)
last = last->next;
last->next = new_node;
then you are changing the data member next of the previous (last ) node.
Though this loop will not work if initially head_ref is equal to NULL.
I am working with linked lists and i fill the structure but when I delete the whole structure and try to print the contents of the linked list (should be null), a list of numbers appear. I know it is probably a memory problem. Any suggestions of how to fix it?
Code for deleting whole linked list:
void destroy(set_elem *head)
{
set_elem *current = head;
set_elem *next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
head = NULL;
}
While your delete function works correctly, it doesn't set the head in the caller to NULL when you do head = NULL; as you are only modifying a local pointer, which causes to your later logic where you are trying to print the values by checking the value of head.
To modify the original pointer, pass a pointer to head and set *head=NULL;
void destroy(set_elem **head)
{
set_elem *current = *head;
/* rest is the same */
*head = NULL;
}
when you copy head pointer passed into the function, head node is unaffected. You have to pass reference to the pointer to the head,then you will be able to delete head pointer. This can be also done by passing a pointer to the pointer to the head of the linked list but I find passing a reference more convenient. Following are the changes to your code.
void destroy(set_elem*& head)
{
set_elem* current = head;
set_elem* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
You are not changing the original head. You should pass the pointer to this head i.e. pointer to a pointer or should return changed head to the caller. Following is the code to return changed head to the caller. There are other answers showing pointer to pointer approach.
set_elem* destroy(set_elem *head) {
set_elem *current = head;
set_elem *next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
head = NULL;
return head;
}
in caller,
head = destroy(head);
You're modifying only the local head pointer
Use a double pointer to modify the head, which would be later used for printing/processing
void destroy(set_elem** head)
{
set_elem* current = *head;
set_elem* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head = NULL;
}