【问题标题】:C++ search for a node in an ordered linked listC++在有序链表中搜索节点
【发布时间】:2020-12-08 09:41:26
【问题描述】:

您好,我有一个使用结构的有序链表。该结构有两个元素:字符串名称和 int id。我正在尝试搜索特定节点,以便可以打印它,但是当我尝试运行代码时,我不断收到“核心转储(分段错误)”错误。

/*
 * search: Auxiliary function that searches for a specific node in the list.
 */
node* search(node* head, int c){  
    node* aux = head; 
    
    while (aux != NULL && aux->id != c)  
        aux = aux->next;  
    return aux;  
}  

/* 
 * showNode: Prints the information of a specific node (search is done by ID).
 */ 
void showNode(node* head, int c) {
    node* aux = head;
    node* resp;

    if (aux != NULL) {
        resp = search(aux, c);
        if(resp->id == c)
            print(resp);
        else
            printf("Node wasn't found");
    } else {
        printf("Error: Empty list. \n");
    }
}

【问题讨论】:

  • 如果resp == nullptr怎么办?
  • if (resp != null && resp->id == c) 之类的。和aux->id > c

标签: c++ list search


【解决方案1】:

我马上就发现了一个问题(尽管可能还有其他问题)。

如果找不到该项目,您的search 函数将返回NULL,但您盲目地检查resp->id == c - 这不太可能结束。

你可以相当容易地解决这个问题,你只需要在showNode()调整你的检查:

// Find a node and return it, or nullptr if not found.

node *search(node *curr, int c) {  
    while (curr != nullptr && curr->id < c)  
        curr = curr->next;
    return (curr != nullptr && curr->id == c) ? curr : nullptr;  
} 

// Find a node and print it (or if it couldn't be found).
void showNode(node *head, int c) {
    node *resp = search(head, c);
    if (resp != nullptr) {
        print(resp);
    } else {
        printf("Node wasn't found");
    }
}

您会看到我还进行了一些其他更改,完整列表如下:

  • 使用更现代的nullptr 而不是NULL
  • search() 中删除aux,因为传入的参数无论如何都是一个副本:你也可以直接使用它(重命名为curr,因为它在技术上不再占据主导地位);李>
  • 一旦我们找到大于或等于我们想要的元素就退出搜索(因为,正如您所说,它是有序的,我假设顺序是升序 - 如果我们正在寻找7 并到达42,除此之外没有机会7 存在)。然后如果相等就返回,否则返回nullptr
  • 消除了尝试取消引用 nullptr 的可能性;
  • 不区分空列表中未找到的项目和非空列表中未找到的项目(价值可疑)。这样可以简化 showNode() 代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多