我有以下代码,我正在将存储的字符串转换为链表。示例: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
笔记 :
如果我将创建功能更改为 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;
}
谢谢!