First, it is important that it works. Due to while(temp->fwd!=NULL) your solution does not work for these scenarios:
A) 1 -- 2 B) 1 -- 3 | | | 3 2 4
Try this instead:
#include <stdio.h> struct node { int data; struct node *fwd; //pointer to next node in the main list. struct node *down; //pointer to a linked list where this node is head. }; struct node *solve(struct node *head) { struct node *temp = head, *fwd; while (temp != NULL) { fwd = temp->fwd; while (temp->down != NULL) { temp = temp->down; } temp->down = fwd; temp->fwd = NULL; temp = fwd; } return head; } int main(int argc, char **argv) { struct node n12 = { 12, NULL, NULL }, n11 = { 11, NULL, &n12 }, n10 = { 10, NULL, &n11 }, n8 = { 8, NULL, NULL }, n7 = { 7, &n10, &n8 }, n9 = { 9, NULL, NULL }, n6 = { 6, NULL, &n9 }, n5 = { 5, &n7, &n6 }, n4 = { 4, NULL, NULL }, n3 = { 3, NULL, &n4 }, n2 = { 2, NULL, &n3 }, n1 = { 1, &n5, &n2 }, *result = solve(&n1); while (result != NULL) { printf("%d%s", result->data, result->down ? " - " : ""); result = result->down; } puts(""); return 0; }
Note: This, of course, does not apply to node->down->fwd . You can solve this problem with a recursive function that remains as an exercise.