c++ - 制作循环链表并找到循环的开头
问题描述
我的任务是在循环链表中找到循环的开头。由于未提供列表,我决定通过获取用户输入的列表大小来创建一个 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;
}
}
}
解决方案
实际返回新列表的最小更改是通过引用传递指针:
void getList(node*&, int );
或者更好地定义指针类型
using nodePtr = node*;
void getList(nodePtr&, int);
推荐阅读
- sql-server - 如何使用存储过程将 SQL 数据记录导出为 CSV 格式?
- python - Yandex Spellchecker API 返回空数组
- r - 如何仅用图例绘制一个空的ggplot?
- mysql - Mysql 多对多选择和排序
- python - 如何在 Cygwin for Windows 10 (x64) 中使用 GDB 调试 python 源代码
- mongodb - 在 MongoDB 中使用 $function new 运算符进行 updateMany 失败
- javascript - 如何计算luxon中两个日期之间的持续时间?
- python - 为什么要使用什么都不做的抽象类?
- javascript - 通过 javascript 录制网站的内部音频
- django - Django覆盖保存方法,在更新模型上复制图像