Singly Linked List insertion

inserting a node at the beginning of singly linked list

Singly Linked List insertion

import code from the create and display nodes and getnode function to assign data click here

  1. create a function inserbeg( )
  2. create a *newnode pointer
  3. call getnode( ) function to assign data to newnode
newnode should be connected to the head node

4.initialize nexnode->next address to the head address

Singly Linked List insertion 1

4 .intialize head to newnode pointer in the else block

Singly Linked List insertion 2
newnode -> next = head;
head = newnode;

program for inserting a node at the beginning of singly linked list

void insertbeg()
{
	node *newnode;
	newnode = getnode();
	if(head == NULL)
	{
		head = newnode;
	}
	else
	{
		newnode -> next = head;
		 head = newnode;
	}
	printf("node inserted successfully\n");
}

inserting a node at the ending of singly linked list

inserting a node at the ending in Singly linked lists

import code from the create and display nodes and getnode function to assign data click here

  1. create a function inserend( )
  2. create a *newnode , *temp pointer from sturcture NODE
  3. call getnode( ) function to assign data to newnode, intialize temp=head
Singly Linked List insertion 3

4.move the temp pointer to every node to access every data by using while condition temp->next=NULL

change value of temp (to access next node) to temp=temp->next

Singly Linked List insertion 4

5.after exiting while temp pointer will be at last node,now connect this last node with the newnode (temp->next=newnode)

Singly Linked List insertion 5
temp = head;
while(temp -> next != NULL)
{
    temp = temp -> next;
}
temp -> next = newnode;

Program for inserting a node at the ending of singly linked list

void insertend()
{
	node *newnode, *temp;
	newnode = getnode();
	if(head == NULL)
	{
		head = newnode;
	}
	else
	{
		temp = head;
		while(temp -> next != NULL)
			{
			temp = temp -> next;
			}
		temp -> next = newnode;
	}
	printf("node inserted successfully\n");
}

inserting a node at the middle of singly linked list

void insertchoice(int p)
{
  int i;
  node *newnode,*temp;
  newnode = getnode();
  temp = head;
  if (newnode==NULL) 
  {
    printf("Unable to allocate memory.");
  }
  else 
  {
    for (i=2;i<=p-1;i++) 
    {
      temp=temp->next;
      if(temp==NULL)
      {
        break;
      }
    }
    
    if(temp!=NULL) 
    {
      newnode->next=temp->next;
      temp->next=newnode;
      printf("DATA INSERTED SUCCESSFULLY\n");
    } 
    else 
    {
      printf("UNABLE TO INSERT DATA AT THE GIVEN POSITION\n");
    }
  }
}
Default image
Vishal Devxo
Vishal Devxo is a DevOps engineer and a Backend developer, he spends all his time for creating good tutorials with better visuals and blogging, developed some projects based on Python-Django, some hacking modules and scripts in python