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;
}
0 Comments