Question

Can anyone please explain this?

struct node 
{ 
    int data; 
    struct node * link; 
} 
main() 
{
    struct node *p, *list, *temp; 
    list = p = temp = NULL; 
    ......................... 
    ......................... 
} 

addbeg() 
{ 
    int x;
    temp=malloc(sizeof(struct node));
    scanf("%d", &x); 
    temp->data=x;
    temp->link = list;
    list=temp;
}

This is a code for entering data in linked list through C language. The code is not complete, but I think its enough for the purpose. Please explain the coding basically these lines:

 temp=malloc(sizeof(struct node));

and

 temp->link = list;
 list=temp;.
Was it helpful?

Solution

malloc() is used to allocate memory - in this case for a new node.

The addbeg() function defined in your code does the following:

  1. Defines a temporary variable x.
  2. Allocates space for a new node.
  3. Inputs an integer (%d code to scanf) and stores it in x.
  4. Stores the value that was saved to x in the data field of the newly allocated node.
  5. Stores the old "head" of the list pointed to by the variable 'list' as a link in the newly allocated node.
  6. Sets the new node to be the new head of the list stored in the variable 'list'.

It's a very basic implementation of a linked list (http://en.wikipedia.org/wiki/Linked_list) of integers.

OTHER TIPS

first line: Allocate memory for a single additional node of the list.

second line: Attach the current list as the continuation after this element.

third line: Make the current element the beginning of a list.

temp and list aren't visible in addbeg, since they're declared in main. They either need to be passed in to addbeg or declared outside of main (global, yuck).

malloc allocates space for a new node.

temp->link = list

and

list = temp

makes that new node the head of your list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top