Reputation: 65
void AddToEnd(double data ,int x, int y, element **list){
element *node, *tmp;
node=*list;
if (data != 0)
{
tmp=malloc(sizeof(element));
tmp->value=data;
tmp->x_element=x;
tmp->y_element=y;
tmp->next=NULL;
if (node !=NULL) {
while (node->next != NULL) node=node->next;
node->next=tmp;
}
else
{
*list=tmp;
}
}
}
How to get off this "if (node !=NULL)/else"? I want to add an element to the end of the list, but without this if/else which i used to adding first element.
Upvotes: 0
Views: 69
Reputation: 29116
You can add one level of indirection and keep a pointer to the current node. Modify the list through this pointer. The initial value is the address of the head. After that, it holds the address of the next
field of the previous node.
void AddToEnd(double data, int x, int y, element **list)
{
if (data != 0) {
element *tmp = malloc(sizeof(*tmp));
tmp->value = data;
tmp->x_element = x;
tmp->y_element = y;
tmp->next = NULL;
while (*list) {
list = &(*list)->next;
}
*list = tmp;
}
}
This code updates the list head when the list is empty.
Upvotes: 1
Reputation: 17880
You can create a dummy head node in main
element *list = malloc(sizeof(element));
list->value=0;
list->x_element=0;
list->y_element=0;
list->next=NULL;
And from here on you can use the AddToEnd
modfied (without if/else) as
void AddToEnd(double data ,int x, int y, element **list){
element *node, *tmp;
node=*list;
if (data != 0)
{
tmp=malloc(sizeof(element));
tmp->value=data;
tmp->x_element=x;
tmp->y_element=y;
tmp->next=NULL;
while (node->next != NULL) node=node->next;
node->next=tmp;
}
}
So your list actually starts from second node in list
Upvotes: 1