Alright so we are back with another blog where we are discussing the only Data Structure in the world of coding that resembles a Train from real life- That's right, It's Linked Lists!
So in this article I will be discussing more ways of inserting nodes in a linked list. Let's get started!
Question : Enter Node at the tail of the Linked List, in between a linked list, at a specific position, deletion of node from the front of a linked list, Printing the list
Whoa! Now that's a lot of work from a dude who has just started with Linked Lists, nevertheless, let's do it, shall we?
Function : Insert after a Given Node
void
insertAfter(Node* previous_node,
int
new_data)
{
if
(previous_node == NULL)
{
cout <<
"the given previous node cannot be NULL"
;
return
;
}
Node* new_node =
new
Node();
new_node->data = new_data;
new_node->next = previous_node->next;
previous_node->next = new_node;
}
Here we created a new node, entered New data in the node,
set the next pointer
of the new node as the same value as next pointer of previous node, set the
pointer of previous node to point to value in the new node.
Function : Insert at tail
void
append(Node* head,
int
new_data)
{
Node* new_node =
new
Node();
Node *last = head;
new_node->data = new_data;
new_node->next = NULL;
if
(head == NULL)
{
head= new_node;
return
;
}
while
(last->next != NULL)
last = last->next;
last->next = new_node;
return
;
}
Here we created a new node, inserted data value into it, made another node
'Last' which we will use to assign to the tail of the linked list, set the
pointer of new node to point to NULL as it is at the end, iterate to the last
value in the list and then set the pointer of last node to point to new node
value. We also run an additional if condition to check if the list is empty
Function : Insert at Nth Position
Node* insertNodeAtPosition(Node* head, int data, int position)
{
Node* new_node= new Node(data); //create a node and insert data inside it
if(head==NULL)
{
return new_node;
}
if(position==0) //head position
{
new_node->next=head;
return new_node;
}
Node* current_node= head;
while(position-1>0) //traverse to the position until position is 0 distance
{
current_node=current_node->next;
position--;
}
new_node->next= current_node->next; //set pointer of new node to pointer of current node
current_node->next= new_node; //set value of next pointer of current node to point to the new node
return head;
}
And that's what I coded!