Hi all, I wrote function to add to elements in the list, but when I call printList function it returns me empty list ! I'm new with linked list in C so I need help and advices ...Thx
Output:
Empty list
List is empty add element at the begining
New node with packet num 245
List is not empty add element at the end
New node with packet num 486
Linked list: Empty
Main:
Code:
int main(){
struct node * start ;
start = NULL;
int i;
/*Check if list is empty*/
if(start == NULL){
printf("Empty list\n");
}else{
printf("List is not empty!\n");
}
start = add_node(start,245);
printf("New node with number %ld\n",start->num);
start = add_node(start,486);
printf("New node with number %ld\n",start->num);
printList(start);
return 0;
}
add_node and printList functions:
Code:
struct node * add_node(struct node * start, int num) {
struct node * temp, *p;
int i;
temp = (struct node *) malloc(sizeof (struct node));
//Enter new value
temp->info = num;
if (start == NULL) {
printf("List is empty add element at the begining\n");
temp->next = NULL; // start = NULL, new element is the last and must point at NULL
start = temp; // start now points not to NULL but to new added element
return start;
}
// Add element to the end of the list
else {
printf("List is not empty add element at the end\n");
p = start;
while (p->next != NULL) {
p = p->next;
}
temp->next = NULL;
p->next = temp;
return temp;
}
}
void printList(struct node *start) {
struct node *tmp = start->next;
printf("Linked list: ");
if (start->next == NULL) {
printf("Empty");
} else {
while (tmp != NULL) {
printf("%d ", tmp->info);
tmp = tmp->next;
}
}
printf("\n");
}