Linked list deletion

why isn’t it deleting node at end

void deleteAtTail(node *head)
{
while(head->next!=NULL)
{

	head=head->next;
}

delete head;

}

please help

sorry i could’nt understand the same . what will happen if i pass it by reference. i am deleting it at tail.

but this is working perfectly fine:

void deleteAtMiddle(node *head , int p)
{
int jump=1;
node *temp;
while(jump<=p-1)
{
temp=head;
head=head->next;
++jump;
}

temp->next=head->next;
delete head;

}

its deleting node at position p.

and the change is being reflected in the linked list … am getting confused please solve my doubt

@gulatigarvita08 please share the whole code. Save it on CB IDE and then share.

please tell … i have sent my code

@gulatigarvita08
Make these changes

void deleteAtTail(node *head)
{
    node *prev;
	while(head->next!=NULL)
	{
        prev = head;
		head=head->next;
	}
    prev->next = NULL;
	delete head;
}

Explanation : In your code, when you reached the tail node, you simply did a

delete head;

While this deleted the node at that place, the second last node still points to this location i.e. after you deleted the node with data = 9, the node with data = 8 has a next pointer which is now pointing to a random memory location. This is the location where the node with data=9 was located but now has some garbage data.
Ideally, we should change the next pointer for 8 and point to it to NULL as this is the new tail of our linked list. Hence the changes to that. I have simply maintained a prev pointer, similar to your deleteAtMiddle function.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.