I have created a very basic link list and it's not outputting anything. I am unable to output anything. What went wrong? I am not getting any kind of error on the console. I am trying C after learning node and react on JS. C is extremely different than JS.
typedef struct node {
int data;
struct node *next;
} node;
//Creates new node
node *createNewNode(int data){
node *tmp = malloc(sizeof(node));
tmp->data = data;
tmp->next = NULL;
return tmp;
}
//adds node at the end
void addNodeAtEnd(node *head, node *nodeToInsert){
node *tmp = head;
//If head is null, make first node your head
if (head==NULL)
{
head=nodeToInsert;
return;
}
//Insert new node at the end
//traverse through whole node to reach the end
while (tmp->next != NULL)
{
tmp=tmp->next;
}
//Finally insert at the last nodes
tmp->next = nodeToInsert;
}
//views all nodes
void viewAllNodes(node *head){
node *tmp = head;
while(tmp->next != NULL){
printf("%d - ", tmp->data);
tmp=tmp->next;
}
}
int main(){
node *head = NULL;
addNodeAtEnd(head,createNewNode(1));
addNodeAtEnd(head,createNewNode(2));
addNodeAtEnd(head,createNewNode(3));
viewAllNodes(head);
}
The function addNodeAtEnd
declared like
void addNodeAtEnd(node *head, node *nodeToInsert);
accepts the pointer head
declared in main
by value. It means that the function deals with a copy of the value of the pointer. Changing the copy does not reflect on the original pointer.
You need to pass the pointer by reference.
In C passing by reference means passing an object indirectly through a pointer to it. Dereferencing the pointer you can get a direct access to the original object.
The function can be declared and defined the following way
//Creates new node
node * createNewNode(int data)
{
node *tmp = malloc(sizeof(node));
if ( tmp != NULL )
{
tmp->data = data;
tmp->next = NULL;
}
return tmp;
}
//adds node at the end
int addNodeAtEnd(node **head, node *nodeToInsert )
{
int success = nodeToInsert != NULL;
if ( success )
{
while ( *head != NULL ) head = &( *head )->next;
*head = nodeToInsert;
}
return success;
}
And in main the function is called like
addNodeAtEnd( &head, createNewNode(1));
Though it would be much better to declare and define the function the following way
//adds node at the end
int addNodeAtEnd(node **head, int data )
{
node *nodeToInsert = createNewNode( data );
int success = nodeToInsert != NULL;
if ( success )
{
while ( *head != NULL ) head = &( *head )->next;
*head = nodeToInsert;
}
return success;
}
And call it like
addNodeAtEnd( &head, 1 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.