Few issues, here:
Code:
void add_tail(struct node **head,struct node *new_node){
struct node *current=*head;
while(current!=NULL){
current=current->next;
}
current->next=new_node; // Consider what you're asking here.
}
You're looping until your current pointer is the NULL pointer. Then you're trying to access the next member of this NULL pointer. Does that make sense? When you traverse through a linked list, you're looking for the pointer who's next member is NULL, not the current object. Secondly, you have another issue where you just kind of hope your next pointer equals NULL without assigning NULL to it. That's bad. Infact, if you don't assign it, then you'll most likely end up with an infinte loop because it will never find the null pointer.
I've taken the liberty of rewriting the code a bit for you. I want you to look at it and see what I did.
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int age;
struct node *next;
};
void add_head(struct node **head,struct node *new_node);
void printList(struct node *head); // There is no reason
void add_tail(struct node *head,struct node *new_node); // to pass a pointer to head in these
// two functions. I changed it.
int main(void){
struct node *head=0;
struct node *newNode;
struct node *newNodeA;
/*create a new Node.Add it to the head*/
newNode=(struct node*)malloc(sizeof(struct node));
newNode->age=2;
add_head(&head,newNode);
printList(head);
/*create a new Node.Add it to the tail*/
newNodeA=(struct node*)malloc(sizeof(struct node));
newNodeA->age=3;
add_tail(head,newNodeA);
printList(head);
getchar();
}
void add_head(struct node **head,struct node *new_node){
new_node->next=*head;
*head=new_node;
}
void add_tail(struct node *head,struct node *new_node){
struct node *current=head;
while(current->next!=NULL){ // Find the last tangible object in the list
current=current->next;
}
current->next=new_node; // Set it's next member to the new node.
current = current->next; // Go to that new tail member
current->next = NULL; // Set it's next member to NULL
}
void printList(struct node *head){
struct node *current=head;
while(current->next!=NULL){ // Find the last tangible object in the list
printf("%d",current->age);
current=current->next;
}
printf("%d\n",current->age); // Print the last member's age.
}