Create Singly Linked List in C Programming



In the previous chapter we have studied Node structure of singly linked list. In this chapter we will be looking into creation of singly linked list.

C Program to Create Singly Linked List :

void creat()
{
char ch;
 do
 {
 struct node *new_node,*current;
 new_node=(struct node *)malloc(sizeof(struct node));
 printf("\nEnter the data : ");
 scanf("%d",&new_node->data);
 new_node->next=NULL;
  if(start==NULL)
  {
  start=new_node;
  current=new_node;
  }
  else
  {
  current->next=new_node;
  current=new_node;
  }
 printf("\nDo you want to creat another : ");
 ch=getche();
 }while(ch!='n');
}

Step 1 : Include Alloc.h Header File

  1. We don’t know, how many nodes user is going to create once he execute the program.
  2. In this case we are going to allocate memory using Dynamic Memory Allocation functions such as Alloc & Malloc.
  3. Dynamic memory allocation functions are included in alloc.h
#include<alloc.h>

Step 2 : Define Node Structure

We are now defining the new global node which can be accessible through any of the function.

struct node {
  int data;
  struct node *next;
}*start=NULL;

Step 3 : Create Node using Dynamic Memory Allocation

Now we are creating one node dynamically using malloc function.We don’t have prior knowledge about number of nodes , so we are calling malloc function to create node at run time.

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

Step 5 : Fill Information in newly Created Node

Now we are accepting value from the user using scanf. Accepted Integer value is stored in the data field.

Tip #1 Whenever we create new node , Make its Next Field as NULL.
printf("\nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;

Step 6 : Creating Very First Node

If node created in the above step is very first node then we need to assign it as Starting node. If start is equal to null then we can identify node as first node -

start == NULL

First node has 3 names : new_node,current,start

if(start == NULL) {    {
   start = new_node;
   curr = new_node;
}

Step 7 : Creating Second or nth node

  1. Lets assume we have 1 node already created i.e we have first node. First node can be referred as “new_node”,”curr”,”start”.
  2. Now we have called create() function again

Now we already have starting node so control will be in the else block -

else
    {
    current->next = new_node;
    current = new_node;
    }

Inside Else following things will happen -

In the else block we are making link between new_node and current node.

current->next = new_node;


Now move current pointer to next node -

current = new_node;