【发布时间】:2021-07-31 07:29:13
【问题描述】:
这里的函数插入似乎有什么问题?我无法理解它。
它应该是链表数据结构中的一个简单插入函数,其中变量需要被复制到分配的内存中,如果没有错误,它应该返回 0。
int insert(char *s, char *p, char *o) {
struct node *new = (struct node *) malloc(sizeof(struct node));
new->Subject = s;
new->Predicate = p;
new->Object = o;
struct node *temp = head;
while (temp->next != NULL ) {
if (strcmp(temp->next->Subject, s) > 0) {
break;
} else if (strcmp(temp->next->Subject, s) == 0) {
if (strcmp(temp->next->Predicate, p) > 0) {
break;
} else if (strcmp(temp->next->Predicate, p) == 0) {
if (strcmp(temp->next->Object, o) > 0) {
break;
} else if (strcmp(temp->next->Object, o) == 0) {
return 1;
}
}
}
temp = temp->next;
}
new->next = temp->next;
temp->next = new;
return 0;
}
【问题讨论】:
-
当列表为空时会发生什么?
head应该为空,并且您将temp设置为它(第 6 行),然后访问temp->next(第 8 行)而不检查temp是否为空。你需要分开考虑这种情况。 -
顺便说一句,我认为如果你实现一个
compare函数,接收两个节点指针并返回一个 int 会很漂亮(-1 表示第一个 arg 较小,0 表示 args 相等,1 表示第一个 arg 更大)。您的while循环将有一个int comp = compare(temp->next, s),然后根据该结果中断或返回或继续。
标签: c linked-list