Insertion in a singly linked list
What is a singly linked list?
A singly-linked list generally known as a linked list consists of two parts, one is data that holds the actual data which we use and the other one is a pointer that refers to the memory location of the next node
Insertion in a singly linked list:
Insertion in a singly linked list can be performed in different ways
- Insertion at beginning of the singly linked list.
- Inserting a new node at the Nth position.
- Insertion at the end in the singly linked list.
- In this article, we will discuss how to perform these types of insertions
Insertion at beginning in a singly linked list:
void insertatStart(int value)
{
Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head=newNode;
}
Insertion at the end in a singly linked list:
void insertatEnd(int value)
{
Node*newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
Node*t = head;
while (t->next != nullptr)
{
t = t->next;
}
t->next = newNode;
}
}
Insertion at Nth position in a singly linked list:
void insertAtNth(int value,int position)
{
Node*newNode = new Node();
newNode->data=value;
int i;
Node*temp=head;
if(position==1)
{
newNode->next=temp;
head=newNode;
return;
}
for(i=1;i<position-1;i++)
{
temp=temp->next;
}
newNode->next=temp->next;
temp->next=newNode;
}
Comments
Post a Comment
feel free to contact me in case of queries