Search code examples
clinked-listnodestemp

how to move nodes from begining to the end in linked list? C


i want to build a program which takes K elements from the begining of the linked list and putting them in the end of the linked link, kinda spin. for example : if there is linked list : 1->2->3->4->5 and k = 2 then the linked list will look like that : 3->4->5->1->2 here is my try, please help me:

void spinfunc(struct node *node_ptr)
{
    int k = 0;
    int count = 0;
    int temp;
    printf("enter a number of the lements from the begin to be deleted - ");
    scanf("%d", &k);
    while (node_ptr != NULL)
    {
        if (count + 1 <= k)
        {
            count++;
            printf("count: %d", count);
            temp = node_ptr->data;
            node_ptr->data = NULL;
        }
        node_ptr = node_ptr->next;
    }
    printf("%d ", temp);

}

Solution

  • It can be done in a more simple steps.

    We only need to change the next pointer of kth node and tail node of list i.e.

    kth node -> next = null
    tail node -> next = head
    

    And then update the head to (k+1)th node.

    Overall logic:

    Traverse the list from beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till end and store pointer to last node also. Finally, change pointers as stated above.

    struct node* spinFunc(struct node *head)
    

    {

    int k = 2; //assuming k = 2 
    // list = 1->2->3->4->5.
    struct node* current = head;
    struct node* newHead = NULL;
    
    int count = 1;
    while (count < k && current != NULL)
    {
        current = current->next;
        count++;
    }
    //Now current is pointing to node 2 
    
    // current points to kth node. Store it in a variable.
    struct node *kthNode = current;
    
    // current will point to last node i.e. node 5 after this loop
    while (current->next != NULL)
        current = current->next;
    
    //last node -> next = head
    current->next = head;
    
    //update the head now
    newHead = kthNode -> next;
    
    kthNode->next = NULL;
    
    //return the new head
    return newHead;
    

    }