Search code examples
cpointerslinked-listdouble-pointer

String to linked list using double pointer


I have the following code I"m converting the string stored into the linked list. Example : ABC A->B->C->NULL

Problems : When printing the list,it is not giving the desired output.Following is the code and sample input/outputs.

Code

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    char ch;
    struct node *next;
}node;
void create(node **head,char ch)
{
    node *new;
    new=malloc(sizeof(node));
    new->next=NULL;
    new->ch=ch;
    if(*head==NULL)
    {
        *head=new;
        printf("%c",(*head)->ch);
        return ;
    }
    while((*head)->next)
    {
        (*head)=(*head)->next;
    }
    (*head)->next=new;


}
void printList(node *head)
{
    printf("\nThe list has - ");
    while(head)
    {
        printf("%c",head->ch);
        head=head->next;
    }
    printf("\n\n");
}
int main()
{
    node *head=NULL;
    int i=0;
    char *str=NULL;
    str=malloc(sizeof(char)*15);
    printf("\nEnter the string - ");
    scanf("%s",str);

    while(str[i]!='\0')
    {
        create(&head,str[i]);
        i++;
    }
    printList(head);
    return 0;
}

Sample Input/Outputs

Input 1

Enter the string - abc 
a
The list has - bc

Input 2

Enter the string - abcde
a
The list has - de

Input 3

Enter the string - ab
a
The list has - ab

Note :

If I change my create function to this , everything just works fine!. I want to know what’s the difference here? Has it something to do with the double pointer??

void create(node **head,char ch)
{
    node *new,*ptr;
    new=malloc(sizeof(node));
    new->next=NULL;
    new->ch=ch;
    ptr=*head;
    if(ptr==NULL)
    {
        ptr=new;
        return;
    }
    while(ptr->next)
    {
        ptr=ptr->next;
    }
    ptr->next=new;

}

Thanks!


Solution

  • There is a issue with your insert function in the first code snipper where you move the *head so by the time you insert the last node to the list the head is pointing to one before the last node

    a->b->c->d
          |
          |
    
    Head is at c now
    

    So you should never move the head and just use temporary variable to get the value of head and move temp.

    a->b->c->d
    |     |
    |     |
    Head  temp
    

    Has it something to do with the double pointer??

    No it is just that in the second snippet you use ptr as temporary pointer and doesn't move head your code works as shown above.