Insert elements in linked list

In this article, we will discuss methods to insert elements into linked list. We can insert elements at start, end or after some element.

Following code inserts the elements at the start, end or after some element.

#include<iostream>
using namespace std;
class Node{
	public:
	int data;
	Node* next;
};
void traverse(Node* n){
	cout<<"The elements are ";
	while(n!=NULL){
		cout<<n->data<<" ";
		n = n->next;
	}
	cout<<endl;
	return;
}
void insert_front(Node** head,int new_data){
	Node* new_node = new Node();
	new_node->data = new_data;
	new_node->next = *head;
	*head = new_node;
}
void insert_last(Node** head,int new_data){
	Node* new_node = new Node();
	new_node->data = new_data;
	new_node->next = NULL;
	if(*head == NULL){
		*head = new_node;
		return;
	}
	Node* last = *head;
	while(last->next!=NULL){
		last = last->next;
	}
	last->next = new_node;
	return;
}
void insert_after(Node* prev,int new_data){
	if(prev==NULL){
		cout<<"Can't insert after NULL";
		return;
	}
	Node* new_node = new Node();
	new_node->data = new_data;
	new_node->next = prev->next;
	prev->next = new_node;
	return;
}
int main(){
	Node* p = NULL;
	for(int i=0;i<10;i++){
		insert_last(&p,i);
	}
	traverse(p);
	insert_front(&p,-1);
	traverse(p);
	insert_last(&p,10);
	traverse(p);
	insert_after(p->next,30);
	traverse(p);
	return 0;
}
linked list insertion
linked list insertion

One Reply to “Insert elements in linked list”

Leave a Reply

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