clinked-list

Move nodes to the end of Linked List function Problem


I'm a student in C programming and I'm just learning the basics for now. I need to write a function that given a linked list in input, put the nodes containing a multiple of 5 and 3 to the end of the list. I'm trying with a sort of recursive approach, but the program crashes. The exercise guidelines say I cannot delete nodes and then recreate them at the end of the list. I must modify pointers.

EDIT: The debugger says it's a segmentation fault problem.

Here there is the image of the debug errors with this list (15 -> 7 -> 2 -> 1 -> 30 -> 25 -> 10) given in input: segfaultdebug

//node is a type I defined for linked list nodes

node *multipleOf3And5ToTail(node *head){

    node *temp2=head;

    if((head->val%3==0)&&(head->val%5==0)&&head!=NULL){

         while(temp2->next!=NULL){
            temp2=temp2->next;
          }

          temp2->next=head;
          head=head->next;
          temp2->next->next=NULL;
          head->next=multipleOf3And5ToTail(head->next);
    }
    else{
         while(((head->val%3!=0)||(head->val%5!=0))&&head!=NULL){
            head=head->next;}
         if((head->val%3==0)&&(head->val%5==0)&&head!=NULL){
            head=multipleOf3And5ToTail(head);
         }
    }
    return head;
}

Solution

  • Thanks guys! I solved my own problem writing a different code.

    bool isMultipleOf3And5(int n){
        return n%3==0 && n%5==0;
    }
    
    node* getTail(node *head){
        while(head->next != NULL)
            head = head->next;
        return head;
    }
    
    node* multipleOf3And5ToTail(node *head){
    
        node *prev=NULL, *curr=head, *succ=NULL, *tail=NULL, *firstMultipleInTail=NULL;
        
        while(curr != NULL){
            
            while(!isMultipleOf3And5(curr->val) && curr->next != NULL){
                prev = curr;
                curr = curr->next;
                succ = curr->next;
            }
            if(curr == firstMultipleInTail || curr->next == NULL)
                break; // if so, we can stop
            
            if(tail == NULL) {
                // needed to check when we arrive again to it
                firstMultipleInTail = curr;
                tail = getTail(curr);
            }
            
            // put the multiple of 3 and 5 in tail
            tail->next = curr;
    
            // to adjust pointers:
            // if the multiple was in head, we advance head
            if(prev == NULL) head = head->next;
            // else we link the prev to the succ
            else prev->next = succ;
    
            // advance curr
            curr = curr->next;
            // set the end of list to NULL
            tail->next->next = NULL;
            // update the tail
            tail = tail->next;
        }
    
        return head;
    }