Reputation: 617
void add ( struct node **q, int num )
{
struct node *temp ;
/* add new node */
temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
temp -> data = num ;
temp -> link = *q ;
*q = temp ;
}
This function is meant for adding a new item at the beginning of the list.
My doubt is that in most of the books the functions functions involving linked lists use pointer to the node structure rather that instance of the struct itself.
void add( struct node *q, int num )
{
struct node temp ;
temp.data = num ;
temp.link = q ;
q = &temp ;
}
Is there a reason the 1st form of the function is preferred or both methods are equally good?
Upvotes: 2
Views: 150
Reputation: 106012
Second method is completely wrong. It does nothing. Node is created when program enters function body and vanished on leaving the function body because it is not allocated dynamically and change to p
will not be reflected to pointer passed in caller function.
Upvotes: 2
Reputation: 40145
The second example is simply wrong.
So you are wrong as well as an example of the question.
The following example probably work.
void add( struct node **q, int num){
static int count = 0;
static struct node pool[1024];
if(count == 1024){
fprintf(stderr, "Sold out!\n");
} else {
pool[count].data = num;
pool[count].link = *q;
*q = &pool[count];
++count;
}
}
One of the reasons for using a pointer and dynamically allocated memory for the node is due to the existence period.
It is possible to use it if you create a node of survival period, such as global variables and static memory.
In addition, it can be used even in the automatic variables such as struct node temp;
. It can be used when list is created inside a function and is local to it, like below :
#include <stdio.h>
struct node {
int data;
struct node *link;
};
void add( struct node *q, int num){
if(num == 10){
for( ; q ; q = q->link)
printf("%d ", q->data);
printf("\n");
} else {
struct node temp;
temp.data = num;
temp.link = q;
add(&temp, num + 1);
}
}
int main(){
add(NULL, 0);
return 0;
}
Upvotes: 1