Hank
Hank

Reputation: 231

C pointer. Getting the null list

Below Code for inserting data after a specified node. When I do a print*** of the node I am getting the null list.

Also, pls suggest some other I/O method.

head: 1 2 3 4 (linked list with four values)

Inserting the data:

insertAfter(struct Node *head){
    int data, insert;
    struct Node *temp = NULL;
    temp = (struct Node *)malloc(sizeof(struct Node));

    scanf("%d", &data); //value in the linked list
    scanf("%d", &insert); // data to be inserted 

    while (head != NULL){
        if (head->data == data){
            temp->data = insert;
            temp->next = n->next;
            head->next = temp;
            printf("data matched \n");
       }
       head = head->next;
    }
    printList(head); //print*** of the node
}

Printing the linkedList:

 void printList(struct Node *head){
     while (head != NULL){
     printf("\n %d", head->data);
     head = head->next;
   }
}

Any help would be appreciated.

Upvotes: 0

Views: 63

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50776

You probably want this:

insertAfter(struct Node *head){
    struct Node *temp = malloc(sizeof(struct Node)); // one line is enough 
                                                     // and casting is useless.    
    int data, insert;
    scanf("%d", &data);
    scanf("%d", &insert);

    struct Node *current = head;                     // head stays at head of list

    while (current != NULL){
        if (current->data == data){
            temp->data = insert;
            temp->next = n->next;
            current->next = temp;
            printf("data matched\n");
        }
        current = current->next;
    }

    printList(head);
}

The printList function seems correct though it is odd that you print the newline beforehead, I'd use this: "%d\n" instead of this: "\n %d".

Disclaimer: this is untested code. All comments are mine.

BTW: it is bad design to do the input inside the insertAfter function. The signature of this function should be:

insertAfter(struct Node *head, int data, int insert);

and the scanf calls should be done before you call insertAfter:

scanf("%d", &data); //value in the linked list
scanf("%d", &insert); // data to be inserted 
insertAfter(head, data, insert);

Upvotes: 2

Related Questions