1

次のコードがあります。リンクされたリストに格納されている文字列を変換しています。例: ABC A->B->C->NULL

問題: リストを印刷するときに、目的の出力が得られません。コードとサンプルの入力/出力を次に示します。

コード

#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;
}

サンプル入力/出力

入力 1

Enter the string - abc 
a
The list has - bc

入力 2

Enter the string - abcde
a
The list has - de

入力 3

Enter the string - ab
a
The list has - ab

ノート :

create 関数を this に変更すると、すべて正常に動作します!. ここで何が違うのか知りたいですか?ダブルポインターと何か関係がありますか??

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;

}

ありがとう!

4

2 に答える 2