how do you insert in linked list. this is that i have.

struct node
{
 int data;
    struct node *next;
}; struct node *head;

void insert(struct node*, char*, int);

int main()
{
    int data;
   struct node *List_A = NULL;

    insert(&List_A, %data);
    return 0;
}


void insert(struct List_A, int data)
{
  struct node * new_node;

  if(List_A == NULL)
  {
      head = ...malloc...;
      head->data = data;
  }
   else
   {
       while(List_A != NULL)
          {
              List_A = List_A->next;
           }
        new_node = ... malloc...;
        new_node->data = data;
        new_node->next = NULL;
        List_A->next = new_node;


   }
}   

To create a new node

allocate memory for the new node

 new_node = (struct node *) malloc( sizeof(struct node) );

next save data for content

     scanf("%d" , &new_node->data);

To insert

struct node *temp = NULL;   //temporary pointer will be used instead of head, head will be a reference for the whole linked list
temp = head;
if(head == NULL){
    head = new_node;     
}
else{
    while(temp->next != NULL){ //until the end of list is not found
        temp = temp->next;
    }
    temp->next = new_node;
}

Edited 4 Years Ago by zeroliken: added info

This article has been dead for over six months. Start a new discussion instead.