singly linked list (deletion)
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
deletion from a singly linked list:
Deletion in a singly linked list can be performed in different ways
- Deletion from the beginning of the singly linked list.
- Deletion from the Nth position.
- Deletion from the end in the singly linked list.
deletion from beginning in a singly linked list:
void insertatStart(int value)
{
Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head=newNode;
}
deletion from 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;
}
}
deletion from 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