Insertion Operation on Singly Linked List

To insert a new node in the given linked list can be performed in 3 positions:

  1. At beginning of linked list
  2. At given node
  3. At the end of linked list

To insert a node at beginning of a Linked List:

  • Create a new node
  • Copy the address of actual first node into address field of new node
  • Make the new node as the Head of the Linked List.
void ins_begin(){
  struct node *newNode;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    newNode=(struct node*)malloc(sizeof(struct node));
    printf("Enter new node:\n");
    scanf("%d",&newNode->data);
    newNode->next=head;
    head=newNode;
  }
}

To insert a new node at given node of a Linked List:

  • Create new node
  • Move a temporary pointer to the given node if exists otherwise skip the process.
  • If given node exists then copy the address present temporary node next field into new node address field
  • Finally, change the address field of temporary node with new node.
void ins_atgiven(){
  int nodeval;
  struct node *newNode,*temp;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    printf("Enter node value:\n");
    scanf("%d",&nodeval);
    newNode=(struct node*)malloc(sizeof(struct node));
    printf("Enter new node:\n");
    scanf("%d",&newNode->data);
    temp=head;
    while(temp->data!=nodeval)
      temp=temp->next;
    if(temp->data==nodeval){
      newNode->next=temp->next;
      temp->next=newNode;
    }
  }
}

To insert a node at end of a Linked List:

  • Create a new node
  • Move temporary node pointer to last of linked list.
  • Change the address field of temporary node with new node.
  • Make the address field of new node with NULL to show the end of linked list.
void ins_end(){
  struct node *newNode,*temp;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    newNode=(struct node*)malloc(sizeof(struct node));
    printf("Enter new node:\n");
    scanf("%d",&newNode->data);
    temp=head;
    while(temp->next!=NULL)
      temp=temp->next;
    temp->next=newNode;
    newNode->next=NULL;
  }
}

Click on the below button for implementation of Singly Linked List with it's operations.

Singly Linked List



Related Programs


  1. Create Singly Linked List with N number of nodes and display.
  2. Perform insertion operation on Singly Linked List.
  3. Perform deletion operation on Singly Linked List.
  4. Reverse of Singly Linked List.
  5. Move last node of Singly Linked List to first.
  6. Swap first and last nodes in a Singly Linked List.
  7. Find the length of Singly Linked List.
  8. Find middle node of Singly Linked List

No comments:

Post a Comment

Total Pageviews