Question description Malar, subash, and Yasir alias Pari are three first-year engineering students of the State Technical Institution (STI), India. While Malar and subash are average students who come from a Middle class, Yasir is from a rich family. Malar studies, engineering as per his father's wishes, while subash, whose family is poor, studies engineering to improve his family's financial situation. Yasir, however, studies engineering of his simple passion for developing android applications. Yasir is participating in a hackathon for android application development. the task is foling the linked list and also need to follow the given procedure. Firstly, Initialize a linked list. Then find the middle point using two pointers at different speeds through the sequence of values until they both have equal values. Divide the linked list into two halves using these pointer named as slow and fast, then find middle. Now reverse the second half of the linked list. At last alternate merge of first and second halves. Print the fold linked list.
C Program


#include <stdio.h>

#include <stdlib.h>

struct node {

    int data;

    struct node *next;

};

void create(struct node **head,int data) {

    struct node *new_node = (struct node *)malloc(sizeof(struct node));

    new_node->data = data;

    new_node->next = NULL;

    struct node **p = head;

    while (*p)

        p = &(*p)->next;

    *p = new_node;

}

void print(struct node *head) {

    while (head) {

        printf("%d ", head->data);

        head = head->next;

    }

    printf("\n");

}

struct node *reverse(struct node *head) {

    struct node *prev = NULL, *curr = head, *nxt;

    while (curr) {

        nxt = curr->next;

        curr->next = prev;

        prev = curr;

        curr = nxt;

    }

    return prev;

}

void merge_halves(struct node *first, struct node *second) {

    while (second) {

        struct node *f = first->next, *s = second->next;

        first->next = second;

        second->next = f;

        first = f;

        second = s;

    }

}

void fold(struct node **head) {

    struct node *slow = *head, *fast = *head;

    while (fast->next && fast->next->next) {

        slow = slow->next;

        fast = fast->next->next;

    }

    struct node *second = slow->next;

    slow->next = NULL;

    merge_halves(*head, reverse(second));

}

int main() {

    int n, data, i;

    struct node *head = NULL;

    scanf("%d", &n);

    for (i = 0; i < n; i++) {

        scanf("%d", &data);

        create(&head, data);

    }

    printf("Link list data:");

    print(head);

    fold(&head);

    printf("Link list data after fold:");

    print(head);

    return 0;

}