链表会在递归搜索列表中不存在的元素时进行核心转储

Linked List would core dump while searching for an element recursively that is not present in the list

#include <iostream>

using namespace std;

class Node{
public:

int data;
Node* next;

};

//Node* head1 = new Node;

void search(int num , Node* head1)
{

if( (head1 != NULL) & (head1->data == num) )
{
    cout << "Yes";
    return ;
}
else if(head1 == NULL)
{
    cout << "No";
    return ;
}
search(num , head1->next);

//return FALSE;
 }

int main() {
int max , n;
cin >> n;
Node* head = NULL;
Node* ptr;
for(int i = 0; i < n ; i++)
{
    int num;
    cin >>num;
    Node* temp = new Node;
    temp->data = num;
    temp -> next = NULL;
    if(head == NULL)
    {
        head = new Node;
        head = temp;
        ptr = new Node;
        ptr = head;
    }
    else
    {
        ptr->next = temp;
        ptr = ptr->next;
    }
    // linked list is made;
    // traversing through the linked list;

    // search for an element;
    //cout << head->data <<"\n";


}
search(6 , head);
// I have assumed 6 won't be there in the list

 }

链表工作正常。我已经能够在没有 运行ning 任何类型的 运行 时间错误的情况下构建列表。我唯一的问题是搜索方法。

当要搜索的元素存在时,它将完美地打印 "YES",但当元素不存在时,运行s 进入 运行 时间错误而不是打印 "NO";

我已经使用递归(有意的)来解决这个问题,因为我对它不太满意。

为了节省时间,您可以忽略 main 函数,因为它 运行 没问题。我只是提供了参考或任何其他有价值的建议。

我还检查了其他关于 SO 的答案,并意识到链表中的大多数 运行 时间错误是因为内存分配不当。我检查了我的代码,发现内存分配已经正确完成,或者我认为是这样。

你的错误在这里

if( (head1 != NULL) & (head1->data == num) )

应该是

if( (head1 != NULL) && (head1->data == num) )

&& 执行 逻辑和 ,另外,如果左侧为假,则不评估右侧。 & 执行 按位和 ,但总是计算双方。

因此,在您的代码中,当 head1 == NULL 然后 head1->data 仍然被计算时,导致空指针的取消引用和崩溃。

只需将 & 更改为 &&

但是你的递归没有问题。