I need to write three separate functions for node deletion in a circular singly linked list (deleteFront(), deleteMiddle() and deleteEnd()). I have to use only tail (last). For some reason, my deleteEnd() function deletes second to the last node. Can anyone please help?
struct node
{
int data;
struct node* next;
};
// some other functions
// 6 -> 5 -> 4 -> 3 -> deleteEnd() does 6 -> 5 -> 3 ->
void deleteEnd(struct node* last)
{
if (last != NULL)
{
if (last->next == last)
last = NULL;
else
{
node* temp = NULL;
node* temp1 = last;
while (temp1->next != last)
{
temp = temp1;
temp1 = temp1->next;
}
temp->next = temp1->next;
delete temp1;
}
}
}
There are several issues with your
deleteEndfunction:There is no way that the caller can get the new
tailreference, because thetailargument is passed by value. Thetailparameter should be a pass-by-reference parameter.The statement after the loop (in the
elseblock) does not remove the correct node. After the loop,temp1->nextwill be equal tolast, and it should be that node that is removed, yet your code removestemp1. You can fix this by changing the loop condition and initialise thetempandtemp1variables to point to one node further in the list.The
elseblock does not updatetail, yet it is clear that it should, since the originaltailnode is deleted.Less of an issue, but in C++ you should not use
NULL, butnullptr.Here is a correction: