C - 链表 - 插入元素未更新 - 仅添加最后一个输入元素 [英] C - Linked list - Insert element not updated - Only adding last input element
问题描述
PREFACE:目标是提示用户输入,将每个元素(输入行)添加到链表中.
PREFACE: The goal is to prompt a user for input, adding each element (input line) into a linked list.
我一直在玩一些来自 Learn-C.org 的示例代码,其中显示了一个链表示例.我修改了代码,使其采用字符串"而不是整数.
I have been playing around with some sample code from Learn-C.org, which shows a linked list example. I have modified the code so that it takes "strings" instead of integers.
我的插入功能如下:
void push(node_t * head, char *data) {
node_t * current = head;
if(head == NULL) {
printf("First element ever!
");
}
else if(current->data == NULL) {
current->data = data;
current->next = NULL;
}
else {
while (current->next != NULL) {
current = current->next;
}
current->next = malloc(sizeof(node_t));
current->next->data = data;
current->next->next = NULL;
}
}
现在,在 MAIN 中,我按如下方式启动列表:
Now, in MAIN, I initiate the list as follows:
node_t * test_list = malloc(sizeof(node_t));
添加元素是通过:
push(test_list, "FOO");
push(test_list, "FEE");
push(test_list, "FAA");
打印列表时,使用print_list(test_list),我得到以下输出:
When printing the list, using print_list(test_list), I get the following output:
FOO
FEE
FAA
问题
但是,我随后包含了一个 while 循环,该循环提示用户输入并将其添加到链表中.
However, I have then included a while loop that prompts user for input and adds this to the linked list.
char command[120];
int counter = 0;
while(counter < 3) {
printf("Enter element: ");
fgets((void *)command, sizeof(command), stdin);
push(test_list, command); //Insert
counter++;
}
然而,这不会将每个元素添加到链接列表中.相反,它将最后一个元素添加到列表中三次.
However, this does not add each element into the link list. Instead, it adds the LAST element into the list three times.
例如,当提供:
Enter element: Argentina
Enter element: Mexico
Enter element: Sweden
列表打印为:
FOO
FEE
FAA
Sweden
Sweden
Sweden
EDIT(添加打印功能)
我的打印功能如下:
void print_list(node_t * head) {
node_t * current = head;
printf("**** Printing list ****
");
while (current != NULL) {
printf("%s
", current->data);
current = current->next;
}
}
我错过了什么,或者:我该如何解决这个问题?任何帮助都受到高度赞赏.
What am I missing, and alternatively: How can I fix this? Any help is highly appreciated.
推荐答案
使用 strdup
返回分配在堆上的字符串的副本.
Use strdup
to return a copy of the string allocated on the heap.
strdup() 函数返回一个指向新字符串的指针,该字符串是字符串 s 的副本.新字符串的内存通过 malloc(3) 获得,可以通过 free(3) 释放.
The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).
node_t *test_list = malloc(sizeof(node_t));
test_list->next = NULL;
test_list->data = NULL;
while(counter < 3) {
printf("Enter element: ");
fgets((void *)command, sizeof(command), stdin);
push(test_list, strdup(command)); //Insert
counter++;
}
这篇关于C - 链表 - 插入元素未更新 - 仅添加最后一个输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!