1

i have a single list non-circular without sentinel and i want to duplicate every node of it. For example, i have 7,5,12,16 and i want to have : 7,7,5,5,12,12,16,16 but i can't create it.Below is my function code for duplicate the nodes(other parts of the program are correct).

    int duplicate_list(listT *list_head) {
    listT *current, *new_node;

    for(current = list_head; current != NULL; current = current->next,counter++) {
            new_node = (listT *)malloc(sizeof(listT));
            if(new_node == NULL) {
                printf("problem in new_node\n");
                free(new_node);
                exit(-1);
            }

            new_node->data = current->data;
            new_node->next = current;
    }
    return(1);
 }

Can someone help me?

1 Answers1

0

You are not inserting duplicate new_node in the list, you are just creating the new nodes in loop. Consider below example for your reference.

    int duplicate_list(listT *list_head) {
    listT *current, *new_node;

    for(current = list_head; current != NULL; current = current->next,counter++) {
            new_node = malloc(sizeof(*new_node));
            if(new_node == NULL) {
                perror("problem in new_node");
                exit(1);
            }

            new_node->data = current->data;
            new_node->next = current->next;
            current->next = new_node;
            current = new_node;
    }
    return(1);
 }
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • 1
    Without any explanation in English, your answer has no interest to a newbie – Basile Starynkevitch Aug 26 '18 at 13:22
  • Most of my comments also apply to your code. In addition: `perror` automatically adds a `:`, a space, and an error reason to the provided message, so having a `\n` in there probably ends up looking ugly. – melpomene Aug 26 '18 at 13:27