C语言 链表节点插入到前面-所有的内容值改变每次我添加一个值



我正在制作一个单链表,其节点具有字符串和指向下一个节点的指针。我写了一个函数来插入到链表的前面。问题是,每当我向链表插入一个新值时,它都会改变所有节点的值。我不知道我哪里出错了。请帮助。下面是代码

#include <stdio.h>
#include <stdlib.h>
typedef struct Elem {
char *word;
struct Elem *next;
} Elem;
void printList (Elem **list)
{
if(!(*list)){
    printf("List is empty");
    return ;
}
Elem *curr;
curr = *list;
while(curr)
{
    printf("%s -- ",(curr)->word);
    curr = (curr)->next;
}
}
void insert_in_front(Elem **list, char *value)
{
if(!*list)
{
    printf("List is empty... creating first noden");
    (*list) = (Elem*) malloc(sizeof(Elem));
    (*list)->word = value;
    (*list)->next = NULL;
    return ;
}
printf("The word in list is %sn",(*list)->word);
Elem *curr = (Elem*) malloc(sizeof(Elem));
if(!curr)
    exit(-1);
curr->word = value;
curr->next = (*list);
printf("the address of curr is : 0x%xn",curr);
(*list) = curr;
printf("the address of list is : 0x%xn",(*list));
}
int main(void)
{
Elem *newList;
newList = NULL;
char inp[15];
while(1)
{
    printf("Enter the string : ");
    scanf("%s",&inp);
    printf("input is %s",inp);
    printf("nthe address of newList is : 0x%xn",newList);

    insert_in_front(&newList, &inp);
    printf("the address of newList is : 0x%xn",newList);
    printList(&newList);
    printf("the address of newList is : 0x%xn",newList);
    printf("n");
}
return 0;
}

你可以复制粘贴代码来运行。输出信息如下:请原谅调试信息。我只是想看看每次插入后指针是否指向新的位置。

Enter the string : hello
input is hello
the address of newList is : 0x0
List is empty... creating first node
the address of newList is : 0x251b010
hello -- the address of newList is : 0x251b010
Enter the string : world
input is world
the address of newList is : 0x251b010
The word in list is world
the address of curr is : 0x251b030
the address of list is : 0x251b030
the address of newList is : 0x251b030
world -- world -- the address of newList is : 0x251b030
Enter the string : testing
input is testing
the address of newList is : 0x251b030
The word in list is testing
the address of curr is : 0x251b050
the address of list is : 0x251b050
the address of newList is : 0x251b050
testing -- testing -- testing -- the address of newList is : 0x251b050
Enter the string : 

提前感谢!

问题是您将所有内容设置为一个变量——inp

你不是在复制,你是在让每个节点指向相同的地址。当您在随后的scanf调用中更改它时,您正在更改每个节点指向的内容。

使用strdup或其他方法创建inp的副本,并将->word分配给新的副本。例如,你可以说:

    insert_in_front(&newList, strdup(inp));

别忘了稍后释放它!

提示:不需要传递双指针给printList。因为你不打算改变任何东西,传递一个双指针只会让你有能力做错误的事情,并在函数作用域之外实际改变指向列表的头指针。它还使函数内部的代码更难理解。将其更改为单个指针,去掉所有的解引用,您甚至可以去掉curr并只使用列表来迭代,因为它只是指针的副本,而不是顶级的实际列表指针。

相关内容

  • 没有找到相关文章

最新更新