this gode is throwing runtime error (SIGSEGV)
Deletion at the middle
@ayu2321 how will it work if your node class is in comments? Also there is no main() etc, do mention it if you are running this code in some special environment
@ayu2321 the problem with this code is that you made head NULL while calculating length, so all operations after that will automatically fail
i am running this code in one of the ide…below mentioned are the details for the same
/* Don’t write main().
* Don’t read input, it is passed as function argument.
* Return output and don’t print it.
* Taking input and printing output is handled automatically.
*/
Node* deleteMid(Node *head) {
int len = 0;
if(head == NULL){
return NULL;
}
else{
Node*temp1 = head;
while(temp1!=NULL){
len++;
head = head->next;
}
Node*temp = head;
Node*prev = NULL;
cout<<“asxdcv”;
for(int i=0;i<(len)/2;i++){
prev = temp;
temp = temp->next;
}
prev->next = temp->next;
delete temp;
return head;
}
}
now i am using temp1 in it still it is giving same error
do temp1 = temp1->next here, else it will go into an infinite loop
yes i have done it now it is giving wrong output
input: 1 2 3 4 5
output: asxdcv1 2 3 17726656 0
@ayu2321 please share the link of the question, and also save the updated code on ide and share its link
hi @ayu2321 the code is working fine after removing the line “delete temp” so dont use that here (it is a good practice to delete dynamically allocated variables in your own codes, but sometimes it may produce errors in environments like these (leetcode also), so you can skip deleting them here)
Also, this code is producing wrong output for even number of nodes. If nodes are even, then you have to delete the first midde node.
if i am doing this with runner technique then also it is giving error
/*if(head == NULL){
return NULL;
}
else if(head->next == NULL){
delete head;
return NULL;
}
else{
Node*slow = head;
Nodefast = head->next;
while(fast!=NULL || fast->next!=NULL){
slow = slow->next;
fast = fast->next->next;
}
delete slow;
return head;
}/
and in the previous code if i am running the loop till (len-1)/2 then it is working fine
@ayu2321 the previous code was fine just place a check whether n is odd or even and find “mid” accordingly for both cases
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.