+ 2

How to delete a node in middle in a singly linked list?

//pls check the prog below // assume head is already declared void del(int num) { node* temp = head; while(temp->next!=NULL) { if((temp->next)->data == num) { node* temp1 = (temp->next)->next; node* temp2 = temp->next; temp2->next=NULL; free(temp2); temp->next = temp1; } } }

25th Apr 2017, 4:08 PM
Nibhrit Mohanty
Nibhrit Mohanty - avatar
1 Resposta
+ 9
// consider cases wherein node to be deleted is found to be at the front, or at the back of the linked list. void del(int num) { node* temp1 = head; node* temp2 = NULL; bool isFound = false; while(temp1 != NULL && !isFound) { if (temp1->data == num) { isFound = true; if (temp1 == head) { head = temp->next; delete temp; } else if (temp1 == tail) { tail = temp2; delete temp; } else { temp2->next = temp1->next; delete temp; } } else { temp2 = temp1; temp1 = temp1->next; } } }
25th Apr 2017, 6:30 PM
Hatsy Rei
Hatsy Rei - avatar