【问题标题】:Insertion and match function in linked list链表中的插入和匹配函数
【发布时间】: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


【解决方案1】:

temp->next 仍然是null 或垃圾值
使用:

new->next = temp

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2021-09-20
    • 2015-11-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多