【问题标题】:Trouble inserting BST node into a List node将 BST 节点插入列表节点时遇到问题
【发布时间】:2019-09-06 02:18:10
【问题描述】:

我正在使用链接列表和 BST 创建客户忠诚度计划类型代码。它使用忠诚度计划列表,每个节点都包含一个客户 ID 的 BST。目前我正在尝试创建一个在列表中搜索忠诚度计划的函数,一旦找到(如果没有则创建)将客户 ID 添加到该节点的 BST 中。但是,在测试时,我在插入新列表节点(insert_at_front)函数上遇到了读取冲突。 任何帮助将不胜感激!

我尝试改变 find_list 函数的函数类型并为其创建包装函数,就像我之前对 BST 的类似函数所做的那样,但我一直迷失在代码中,而且似乎更多地破坏了它。

list.h header file:
typedef struct listNode {
    char* name; //Name of company
    BST *customer;  //Tree of customer ID's
    struct listNode *next; //Pointer for next compnay
} *ListNodePtr;
void option_insert(List *self) {
    char* input_loyalty;
    int input_ID;

    printf("What loyalty program do you wish to add a customer to?  \n");
    scanf("%s", &input_loyalty);
    printf("What is the customer ID \n");
    scanf("%d", &input_ID);

    find_list(self, input_loyalty, input_ID);
}

void find_list(List *self, char* data, int ID) {
    ListNodePtr current = self->head;

    if (current != NULL) {
        if (current->name == data) {
            insert_bst(self->head->customer, ID);
        }
        else {
            current = current->next;
        }
    }
    else {                          
        insert_at_front(self, data);
        insert_bst(self->head->customer, ID);
    }

}

void insert_at_front(List *self, char* data) {
    int n = strlen(data);
    ListNodePtr new_node = malloc(n * sizeof(char*));
    strcpy(new_node->name, data);

    new_node->next = self->head;
    self->head = new_node;
}

我已经包含了问题中使用的函数,但请注意它们在不同的 .c 文件中是分开的。 (但是这应该没有区别)如果需要我当然可以提供更多代码

【问题讨论】:

  • 有什么理由必须是链表而不是std::vector
  • 这是学校项目的一部分,需要它使用这些数据结构@Chipster
  • 哦。这是有道理的。
  • ListNodePtr new_node = malloc(n * sizeof(char*)); 你能解释一下这条线吗?看起来很不对劲,但也许我错过了什么。
  • 你确定这是一门 C++ 课程吗? Stop Teaching C ;-)

标签: c++ list


【解决方案1】:

答案可能就在您使用malloc() 中。您正在根据数据的大小而不是结构的大小创建内存。

我还应该提到,如果您使用的是 C++(而不是 C),那么学习如何使用 new 关键字可能会更好。

不管怎样,如果你仍然决定使用 malloc,试试这个吧:

void insert_at_front(List *self, char* data) {
    int n = strlen(data);
    ListNodePtr new_node = malloc(sizeof(listNode)); // note, we're using the size of a node instead
    new_node->name = malloc(n * sizeof(char)); // now, we need to allocate the string too.

    strlcpy(new_node->name, data, n); // if you want to use a "secure" copy

    new_node->next = self->head;
    self->head = new_node;
}

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多