【发布时间】:2016-10-08 17:09:46
【问题描述】:
我一直在尝试编写一个将字符串插入到链表开头的程序,但是其中出现了一个小问题。我的代码如下。
#include <stdio.h>
#include <stdlib.h>
struct node{
char* data;
struct node* next;
};
void insIni(struct node** hp, char* x){
struct node* tmp = (struct node *)malloc(sizeof(struct node));
tmp->data = x;
tmp->next = *hp;
*hp = tmp;
}
void printList(struct node* h){
struct node* tmp = h;
printf("\nList contents: \n");
while (tmp != NULL){
printf("%s, ", tmp->data );
tmp = tmp->next;
}
printf("\n");
}
int main(int argc, char const *argv[]){
struct node* head = NULL;
char word [256];
scanf("%s", word);
insIni(&head, word);
scanf("%s", word);
insIni(&head, word);
scanf("%s", word);
insIni(&head, word);
printList(head);
return 0;
}
我在链表的开头插入一个新字符串后,前面的元素也被更改为与刚刚插入的字符串相同,我该如何更改我的代码,以便链接的前面的元素列表保持不变,只添加开头的元素?
例如,如果我写 A B C,链接列表最终会打印为 C、C、C,而不是 C、B、A,。
【问题讨论】:
-
它可以工作,但是 main() 中的
scanf("%s", word);每次都会将输入读入相同的字符数组。您可以将 isnsIni() 中的tmp->data = x;替换为tmp->data = strdup(x); -
好的,该更改似乎解决了我的问题,但是在编译时我收到以下警告:内置函数“strdup”的隐式声明不兼容。这很危险吗?如果是这样,我该如何删除它?
-
您需要
#include <string.h>才能使用 strdup() (注意:strdup 有点非标准) -
strdup 是 POSIX,这是一个非常好的标准
标签: c data-structures linked-list