Reputation: 69
I've been studying linked lists in C and regarding the append function, I came across the following code:
struct node
{
int data;
struct node *next;
}*head;
void append(int num)
{
struct node *temp,*right;
temp= (struct node *)malloc(sizeof(struct node));
temp->data=num;
right=(struct node *)head;
while(right->next != NULL){
right=right->next;
}
right->next =temp;
right=temp;
right->next=NULL;
}
In order to save a line of code, wouldn't it be possible to just add NULL to the temp's next atribute? like so:
void append(int num)
{
struct node *temp,*right;
temp= (struct node *)malloc(sizeof(struct node));
temp->data=num;
temp -> next = NULL;
right=(struct node *)head;
while(right->next != NULL){
right=right->next;
}
right->next =temp;
}
Upvotes: 3
Views: 8617
Reputation: 1729
If you want to "save lines", you could also use calloc, instead of malloc, which zeros your bytes, but that would be LESS clear.
It does save you a line of code, and it is arguable clearer. I think your proposed code change is an improvement in that it separates creation of the new node from placing it.
If this is production code I would probably let sleeping dogs lie. But while we are all chiming in here is how I would implement the same function.
struct node
{
int data;
struct node *next;
};
struct node* init_node(int num)
{
struct node * temp = malloc(sizeof(struct node));
temp->data = num;
return temp;
}
void append(struct node* n, struct node* list)
{
while(list->next != NULL){
list=list->next;
}
list->next =n;
n->next=NULL;
}
Upvotes: 0
Reputation: 58271
Yes you are correct. In-fact I will further reduce the length of code by writing separate function that allocate and intialize data as follows:
struct node * getnode(int date){
struct node *temp = malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
return temp;
}
// assuming list have more than one elements: demo code
void append(struct node *head, int num){
struct node *right = head;
while(right->next != NULL){
right=right->next;
}
right->next = getnode(num);
}
This get node function can be useful in other part of code e.g insertatfist()
, insert()
Btw: Don't cast the returned address of malloc()
and calloc()
.
May be you like to write struct node* getnode(int data, struct node* next)
function that also set next node address.
call it as:
To insert last node:
curt->next = getnode(num, NULL);
To insert between curt
node and curt->next
.
curt->next = getnode(num, curt->next);
Upvotes: 2
Reputation: 4476
It certainly is possible to do it that way in this way, However, I see that the code in the first approach is more readable(very small more) to my eyes. However you aren't going to save much.
But don't try to do these kind of optimizations for all programs, give readability more importance than saving a few lines of code. Reason is that compiler is anyways going to do the optimization.
Upvotes: 1