【问题标题】:Making a circular linked list and finding the beginning of the loop制作循环链表并找到循环的开头
【发布时间】:2018-05-04 05:08:25
【问题描述】:

我的任务是在循环链表中找到循环的开头。由于未提供列表,我决定通过获取用户输入的列表大小来创建一个 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;
        }
    }
}

【问题讨论】:

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

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


【解决方案1】:

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

 void getList(node*&, int );

或者更好的定义指针类型

 using nodePtr = node*;

 void getList(nodePtr&, int);

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2020-10-15
    • 2015-08-01
    • 2019-01-30
    相关资源
    最近更新 更多