[英]C++ search for a node in an ordered linked list
Hi I have an ordered linked list using structs.您好,我有一个使用结构的有序链表。 The struct has two elements: string name and int id.
该结构有两个元素:字符串名称和 int id。 I am trying to search for a specific node so I can then print it but I keep getting the "Core Dump (Segmentation fault)" error when I try to run the code.
我试图搜索一个特定的节点,以便我可以打印它,但是当我尝试运行代码时,我不断收到“核心转储(分段错误)”错误。
/*
* 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");
}
}
I see one problem straight away (though there may be others).我立即看到一个问题(尽管可能还有其他问题)。
Your search
function will return NULL
if the item cannot be found, yet you blindly go and check if resp->id == c
- that's unlikely to end well.如果找不到该项目,您的
search
function 将返回NULL
,但您盲目地搜索 go 并检查是否resp->id == c
- 这不太可能结束。
You can fix that reasonably easily, you just have to adjust your check in showNode()
:您可以很容易地解决这个问题,您只需要在
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");
}
}
You'll see I've made some other changes as well, the complete list is:你会看到我也做了一些其他的改变,完整的列表是:
nullptr
rather than NULL
;nullptr
而不是NULL
;aux
in search()
, as the parameter passed in is a copy anyway: you may as well just use that (renamed to curr
since it's technically doesn't stay the head any more);search()
中的aux
,因为传入的参数无论如何都是一个副本:您也可以使用它(重命名为curr
因为它在技术上不再保留头部);7
and get to 42
, there's no chance 7
will exist beyond that).7
并得到42
,除此之外7
不可能存在)。 Then we just return it if it's equal, or return nullptr
if not;nullptr
;nullptr
;nullptr
的可能性;showNode()
code.showNode()
代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.