繁体   English   中英

C++ 在有序链表中查找节点

[英]C++ search for a node in an ordered linked list

您好,我有一个使用结构的有序链表。 该结构有两个元素:字符串名称和 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");
    }
}

我立即看到一个问题(尽管可能还有其他问题)。

如果找不到该项目,您的search function 将返回NULL ,但您盲目地搜索 go 并检查是否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因为它在技术上不再保留头部);
  • 一旦我们找到一个大于或等于我们想要的元素就退出搜索(因为,如您 state,它是有序的,我假设顺序是升序的 - 如果我们正在寻找7并得到42 ,除此之外7不可能存在)。 如果相等则返回,否则返回nullptr
  • 消除尝试取消引用nullptr的可能性;
  • 不区分空列表中未找到的项目和非空列表中未找到的项目(可疑值)。 这允许简化showNode()代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM