- 论坛徽章:
- 0
|
本帖最后由 zehn_w 于 2012-08-15 09:31 编辑
昨天面试题目中的一小道题,主要是要求查询链表中是否有相同的单词,然后把生词添加到链表中。
我的代码:- int add_word_to_list(list_node *head, const char *word)
- {
- list_node *node;
- int i;
- head = head->next;
- while (head->next){
- //if (strcmp(head->word, word))
- if (strcmp(head->word, word) == 0)
- return (1);
- head = head->next;
- }
- node = (list_node *)malloc(sizeof(list_node));
- if (NULL == node)
- return (-2);
- // strcpy(node->word, word, 20);
- strncpy(node->word, word, 20);
- /* 原代码, node = head->next 好丢人~ 哈哈 */
- // node = head->next;
- // node->next = NULL;
- /* 改正 */
- head->next = node;
- node->next = NULL;
- return (0);
- }
复制代码 结构体定义:- typedef struct list_node{
- char word[21];
- struct list_node *next;
- }list_node;
复制代码 然后面试官问2个问题:
1. 自己说说代码中还存在哪些隐患。
2. 排除这种方法,要求一个更高效的方法。
对于第1个问题,因为是自己写的,所以自己以为没什么大问题。(把错误修改了,谢谢大家的指导!)
对于第2个问题没有答出来,这里求大家指导一下。
代码还有其他问题也请指正,谢谢~!
|
|