Linked list basic insertion operations in C++

In this tutorial, we are going to learn about all linked list basic insertion operations in C++.

Linked list basic insertion operations

Let us start with inserting a node at the beginning. In this particular case, we create a new node and link it with the head node. After that, we will update the head node to the newly created node. Every time we will insert an element in the beginning head node is updated.

Inserting node in the beginning in Linked List

Below is our C++ code:

// Inserting node in the beginning
class node{
public:
	int data;
	node *next;
	node(int d){
		data=d;
		next=NULL;
	}
};
void insert_beginning(node *&head,int data)
{
  node *n=new node(data);
  n->next=head;
  head=n;
}

Now we will try to insert a node in the tail of a linked list. If the linked list is empty then we will point it to head as well as NULL. Otherwise, the last node will be connected to this node and NULL will be updated by connecting it to the current element.

Inserting node in the tail in Linked List

// Inserting node in the tail
class node{
public:
  int data;
  node *next;
  node(int d){
    data=d;
    next=NULL;
  }
};
void inserttail(node *&head,int data)
{
  if(head==NULL)
  {
    head=new node(data);
    return;
  }
  node *tail=head;
  while(tail->next!=NULL)
  {
    tail=tail->next;
  }
  tail->next=new node(data);
  return;
}

At last, we will try to insert a node at any position in the linked list. To insert a node at any position we need to make a length function. It will help us to reach that position in which we will insert our new node. After reaching that position we will update the links and link it to the element which we are going to insert.

Inserting node at any position  in Linked List

// Inserting node at any position
public:
  int data;
  node *next;
  node(int d){
    data=d;
    next=NULL;
  }
};
int length(node *head)
{
  int len=0;
  while(head!=NULL)
  {
    head=head->next;
    len+=1;
  }
  return len;
}
void insertmiddle(node *&head,int data,int p)
{
  if(head==NULL || p==0)
  {
    insert(head,data);
  }
  else if(p>length(head))
  {
    inserttail(head,data);
  }
  else
  { 
    int jump=1;
    node *temp=head;
    while(jump<=p-1)
    {
      temp=temp->next;
      jump+=1;
    }
    node *n=new node(data);
    n->next=temp->next;
    temp->next=n;
  }
}

You may also learn:

Find if Linked List contains cycle in Java

Introduction to Single Linked List

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.

Leave a Reply

Your email address will not be published. Required fields are marked *