我有以下代码 我正在转换存储在链表中的字符串。 示例: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
注意:
如果我将我的创建功能改为此,一切正常! 我想知道这里的区别是什么? 它与双指针有关吗?
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;
}
谢谢!
答案 0 :(得分:3)
在第一个代码段中你的插入函数存在一个问题,你移动*head
所以当你将最后一个节点插入列表时,头指向最后一个节点之前的一个
a->b->c->d
|
|
Head is at c now
所以你永远不应该移动头部,只需使用临时变量来获取head的值并移动temp。
a->b->c->d
| |
| |
Head temp
它与双指针有关吗?
不,只是在第二个代码段中,您使用ptr
作为临时指针并且不会移动代码,如上所示。
答案 1 :(得分:0)
Gopi已经指出了你的代码的问题。如果区分将第一个节点插入空列表(在这种情况下必须更新head
)并附加到现有列表的两种情况,则可以使用该建议插入新节点。 (你已经抓住了这两个案例。)
但是指向指针的策略增加了一个间接级别,你可以在这里使用它而没有这种区别:head
保存指向头节点的指针。如果使用head
遍历列表,head
应始终指向指向当前节点的指针。当前节点为NULL
时,分配新节点,即覆盖指针:
void create(node **head, char ch)
{
/* create new node */
node *nd = malloc(sizeof(*nd));
nd->next=NULL;
nd->ch=ch;
/* advance to end of list */
while (*head) {
head = &(*head)->next;
}
/* assign */
*head = nd;
}
顺便说一下,你的第二个功能不能正常工作,因为你永远不会更新头部。你会得到一个空列表和内存泄漏。