Thursday, 9 November 2017

Linked List : Singly linked list : Insertion

Insert node at Start/First Position in Singly Linked List

Inserting node at start in the SLL (Steps):
  1. Create New Node
  2. Fill Data into “Data Field
  3. Make it’s “Pointer” or “Next Field” as NULL
  4. Attach This newly Created node to Start
  5. Make newnode as Starting node
void insert_at_beg()
{
struct node *new_node,*current;

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

 if(new_node == NULL)
    printf("nFailed to Allocate Memory");

 printf("nEnter the data : ");
 scanf("%d",&new_node->data);
 new_node->next=NULL;

   if(start==NULL)
   {
   start=new_node;
   current=new_node;
   }
   else
   {
   new_node->next=start;
   start=new_node;
   }
}

Diagram :
insert_start
Attention :
  1. If starting node is not available then “Start = NULL” then following part is executed
if(start==NULL)
       {
       start=new_node;
       current=new_node;
       }
  1. If we have previously created First or starting node then “else part” will be executed to insert node at start
else
       {
       new_node->next=start;
       start=new_node;
       }

No comments:

Post a Comment