C++ 制作循环链表并查找循环的开始

C++ 制作循环链表并查找循环的开始,c++,loops,pointers,linked-list,segmentation-fault,C++,Loops,Pointers,Linked List,Segmentation Fault,我的任务是在循环链表中找到循环的开始。由于没有提供列表,我决定通过获取列表大小的用户输入来创建一个liat,然后使用该大小运行一个for循环。最后一个输入(最后一个节点)将指向链表中的某个位置以创建一个循环。我创建链表的函数正在工作,如果我在从用户那里获取输入时打印了head->data,它将打印正确的值,但是当我在main中调用该函数时,head指针指向NULL,我得到了一个分段错误。有人能看看我的代码并解释为什么会发生这样的事情吗 #include <iostream> usi

我的任务是在循环链表中找到循环的开始。由于没有提供列表,我决定通过获取列表大小的用户输入来创建一个liat,然后使用该大小运行一个for循环。最后一个输入(最后一个节点)将指向链表中的某个位置以创建一个循环。我创建链表的函数正在工作,如果我在从用户那里获取输入时打印了head->data,它将打印正确的值,但是当我在main中调用该函数时,head指针指向NULL,我得到了一个分段错误。有人能看看我的代码并解释为什么会发生这样的事情吗

#include <iostream>

using namespace std;

struct node{

    int data;
    node *next;
};

node *head = NULL;
node *tail = NULL;
node *slow = NULL;
node *fast = NULL;

int findLoop(node * head);
void getList(node * head, int listSize);
bool isEmpty(node * head);

int main(){
int listSize;
    cout <<"\nEnter the size of the list: ";
    cin >> listSize;

getList(head, listSize);
if(head != NULL){
cout << "\n\n\nprinting head " << head->data; //Seg Fault
}
else{
    cout << "Head is NULL" << endl;
}
findLoop(head);

    return 0;
}

int findLoop(node *head){
    slow = head;
    fast = head;
    if(head == NULL){
        cout << "\nThe list is empty\n";
    }
    bool isLoop = false;
    while(slow != NULL && fast != NULL){ 
        if(slow == fast && isLoop == false){
            slow = head;
            isLoop = true;
        }
        else if(slow == fast && isLoop == true){
            cout <<"\nThe loop starts at: ";
            return slow->data;
        }
        slow = slow->next;
        fast = fast->next->next;
    }
    cout <<"\nThere is no loop\n";
    return 0;
}
void getList(node * head, int listSize){

    int userData;
    for(int i=0; i<listSize; i++){
        node *temp = new node;
        cout <<"\nEnter a number: ";
        int NodeValue = 0;
        cin >> NodeValue;
        temp->data = NodeValue;
        if(head == NULL){   
            head = temp;
            cout << head->data << endl; //Test for appropriate pointing.
        }
        if(tail != NULL){
            tail->next = temp;// point to new node with old tail
        }
        tail = temp;// assign tail ptr to new tail
        temp->next = tail;
        if(i == listSize-1){
            node *temp2;
            temp2 = head;
            int iNumber = rand() % i;
            for(int j=0; j<iNumber; j++){
                temp2 = temp2->next;
            }
            tail->next = temp2;
        }
    }
}
#包括
使用名称空间std;
结构节点{
int数据;
节点*下一步;
};
node*head=NULL;
node*tail=NULL;
node*slow=NULL;
node*fast=NULL;
int findLoop(节点*头部);
void getList(节点*头,int listSize);
布尔为空(节点*头部);
int main(){
int列表大小;
cout列表大小;
getList(head,listSize);
if(head!=NULL){

cout实际返回新列表的最小更改是通过引用传递指针:

 void getList(node*&, int );
或者最好定义指针类型

 using nodePtr = node*;

 void getList(nodePtr&, int);

您通过值传递
head
,因此从
getList
返回时将无法观察“本地”分配的
head