Blooddy
Blooddy

Reputation: 13

Making a circular linked list and finding the beginning of the loop

my assignment is to find the beginning of a loop in a circular linked list. Since the list is not provided i decided to make a liat by getting the user input for the size of the list then run a for loop with that size. The very last input (last node) is going to point somewhere in the linked list to create a cycle. My function to create the linked list is working, if i cout the head->data while getting the input from the user it prints the right value but when i call the function in the main the head pointer points to NULL and i get a segmentation fault. Can someone take a look at my code and explain why something like that is happening?

#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;
        }
    }
}

Upvotes: 0

Views: 129

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

Minimal change to actually return new list would be passing pointer by reference:

 void getList(node*&, int );

or better do define pointer type

 using nodePtr = node*;

 void getList(nodePtr&, int);

Upvotes: 0

Related Questions