制作循环链表并找到循环的开头

时间:2018-05-04 05:08:25

标签: c++ loops pointers linked-list segmentation-fault

我的任务是在循环链表中找到循环的开头。由于没有提供列表,我决定通过获取列表大小的用户输入来制作一个liat然后运行具有该大小的for循环。最后一个输入(最后一个节点)将指向链表中的某个位置以创建一个循环。我创建链接列表的功能是有效的,如果我在获取用户输入的同时输入head->数据它会输出正确的值,但是当我在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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

 void getList(node*&, int );

或者更好地定义指针类型

 using nodePtr = node*;

 void getList(nodePtr&, int);