Node* deleteNode(Node* head, int key) {
if(head == NULL){
return NULL;
}
//if their is only one node in list
if(head -> data == key && head -> next == head){
delete(head);
head = NULL;
return NULL;
}
// if first node is to be deleted
Node* last = head;
Node* temp = head;
while(last -> next != temp){
last = last -> next;
}
last -> next = temp -> next;
delete(temp);
head = last -> next;
return head;
while(last -> next != head || last -> next -> data != key){
last = last -> next;
}
Node* dum = last -> next;
last -> next = dum -> next;
delete(dum);
return head;
}
these are the test cases those are getting wrong
Test Case Input
1 2 3 4 5 -1
3
Your Output
2 3 4 5 -1
Desired Output
1 2 4 5 -1
one more is their that's wrong
Test Case Input
1 2 3 4 5 -1
6
Your Output
2 3 4 5 -1
Desired Output
1 2 3 4 5 -1
your problem is so simple, you wrote :
without the
ifcondition that checks the condition called if first node is to be deleted, your code will always delete the first node for any key is entered even if it's not found as you didn't check for the conditionif (head->data == key)but this isn't the case, also the logic of deleting a node in your linked list is incorrect, for the lines where you wrote:this assumes that there is always a node to delete even if the node isn't found, your code will delete a node if the value you are searching for isn't found.
I modified your code and this is the edited code:
since this is a circular linked list, deleting a node from the last is the same as deleting one from the middle and it's the same as deleting the head one but the only corner case is when you are deleting the head node, you should change the head node, that's why you will find this line in my code:
if (temp1 == head)I added some comments, thought might be helpful, also in my code, the
temp1pointer is the ahead pointer that is used to detect the node we are searching for and thetemp2pointer is the one used in deletion, to avoid infinite loop if the node isn't found, I loop tilltemp1come back to its starting position.