samedi 6 juillet 2019

how to fix function reversebetween as it gives segmentation fault?

here i am trying a non recursive solution of reverse a sublist of a given linked list as We are given a linked list and positions m and n. We need to reverse the linked list from position m to n but is gives segmentation fault below my code is given in which reversebetween fuction has some segmentation fault... // C program to reverse a linked list // from position m to position n #include #include

// Linked list node 
struct ListNode { 
    int data; 
    struct ListNode* next; 
}; 

ListNode* reverseBetween(ListNode* A, int B, int C) {

     ListNode *p=A,*q=A,*cur,*pre,*nex;
     int i=1,j=1;
     if(C-B==0)
     return A;
     if(B!=1)
     {
     while(i!=B-1)
     {
         p=p->next;
         i++;

     }}
     while(j!=C)
     {
         q=q->next;
         j++;

     }
     if(B==1)
     {
         cur=A;
         A=q;
     }
    //  p->next->next=q->next->next
    //  p->next=q->next;
    else{
     cur=p->next;

     p->next=q;
     }
     nex=cur->next;
     cur->next=q->next;
     while(nex!=q->next||nex!=cur){
     p=cur;
     cur=nex;
     nex=cur->next;
     cur->next=p;}
          return A;
}
void print(struct ListNode* A) 
{ 
    while (A != NULL) { 
        printf("%d ", A->data); 
        A = A->next; 
    } 
    printf("\n"); 
} 

// function to add a new node at the 
// begining of the list 
void push(struct ListNode** A_ref, int new_data) 
{ 
    struct ListNode* new_node = new ListNode; 
    new_node->data = new_data; 
    new_node->next = (*A_ref); 
    (*A_ref) = new_node; 
} 

// Driver code 
int main() 
{ 
    struct ListNode* A= NULL; 
    push(&A, 70); 
    push(&A, 60); 
    push(&A, 50); 
    push(&A, 40); 
    push(&A, 30); 
    push(&A, 20); 
    push(&A, 10); 
    reverseBetween(A, 3, 6); 
    print(A); 
    return 0; 
} 

error message Segmentation Fault (SIGSEGV)

Aucun commentaire:

Enregistrer un commentaire