简体   繁体   English

如何在链接列表中输入单词?

[英]How do i input words to linked list?

I had a doubly linked list capable of holding characters in each node. 我有一个双向链表,能够在每个节点中保存字符。 This is what I do to input characters to each node. 这就是我要向每个节点输入字符的操作。

printf("Enter string of characters for the list: ");
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
    Insert(s[i],&Header1);

Now i wish to modify the list to store words in each node.The input provided by the user is a sentence. 现在我希望修改列表以在每个节点中存储单词。用户提供的输入是一个句子。 How do i make sure each word(separated by space) gets into a node of the list? 如何确保每个单词(以空格分隔)进入列表的节点?

while ( sscanf( sentence, "%s", &node_value ) == 1 )
{
  //Call to insert into your list goes here
  //Each pass node_value will be the next word
}

NOTE: You will have to pass node_value by value into your list, otherwise all your values will be the same reference! 注意:您将必须按值将node_value传递到列表中,否则所有值将是相同的引用!

char *word;
while (NULL != (word = strtok(s, " ."))) {
    Insert(word, &Header1);
}

You need to modify the node as 您需要将节点修改为
struct node {
node *prev;
char *data;
node *next;
}


and change the scanf to ' fgets . 并将scanf更改为' fgets
Note: I have declared data as a char * , so you cannot use strncpy. 注意:我已将数据声明为char * ,因此您不能使用strncpy。 If you want to copy the string(instead of assigning pointer), then you should malloc the data. 如果要复制字符串(而不是分配指针),则应该malloc数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM