gpt4 book ai didi

c++ - C++程序因链接列表而崩溃

转载 作者:行者123 更新时间:2023-12-03 08:50:06 27 4
gpt4 key购买 nike

嗨,我对链接列表有疑问。尝试调用函数以搜索链表中的元素后,程序崩溃。我正在生成数组,然后尝试制作链表列表数组元素。现在,当我尝试在链接列表中找到0时,它崩溃了,我也不知道为什么。感谢您的考虑

#include <iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

//ARRAY GENERATOR
int *gen_arr(int V[], int n, int dg, int gg){
srand(41);
for(int i=0; i<n; i++){
V[i]=1+(rand() % gg) ;
}
return V;
}

struct node{
int data;
node* next;
};

void SearchRecursive(node* Ptr, int number);
int main(){
int dg,gg;
int n=10;
int* V = NULL;
V = new int[n];

cout<<"Unesite vrijednost donje granice: "<<endl;
cin>>dg;
cout<<"Unesite vrijednost gornje granice: "<<endl;
cin>>gg;

V[n]=*gen_arr(V, n, dg, gg);
/*for(int i=0;i<n;i++){
cout<<V[i]<<" ";
}*/
node * nx = new node;
node* head = nx;
node* t = nx;
nx->data=V[0];
for(int i=1;i<n;i++){
nx = new node;
nx->data = V[i];
t->next = nx;
t = nx;
}
nx->next=NULL;

t = head;
cout<<endl;
while(t != NULL){
cout<<t->data<<" ";
t = t->next;
}

cout<<endl;
cout<<"IIII"<<endl;
clock_t k;
k = clock();
SearchRecursive(head, 0);
k = clock()-k;
printf( "Vrijeme trajanja je %dms\n",k );

return 0;
}

void SearchRecursive(node* Ptr, int number){
if(Ptr == NULL){
cout<<"-1"<<endl;
}
else if(Ptr->data == number){
cout<<"Pronadeno"<<endl;
}
else{
SearchRecursive(Ptr->next, number);
}
}

最佳答案

首先,您的生成器似乎不正确。更正的版本,返回值在[dg,gg)范围内:

//ARRAY GENERATOR
int *gen_arr(int V[], int n, int dg, int gg){
srand(41);
for(int i=0; i<n; i++){
V[i]=dg+(rand() % (gg-dg));
}
return V;
}

您能否更具体地说明什么导致程序崩溃?

关于c++ - C++程序因链接列表而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43424757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com