C++ C++;遍历链表时的分段错误

C++ C++;遍历链表时的分段错误,c++,linked-list,segmentation-fault,C++,Linked List,Segmentation Fault,我正在编写一个程序来查找链表中最后一个节点的第n个。该程序生成正确的输出,但是,当我运行该程序时,我在while(fast)行中得到一个分段错误。当我使用print语句调试程序时,我注意到while(fast)即使fast指针为NULL(即fast超出列表末尾)也会被执行 关于如何修复分割错误有什么建议吗 这是我的密码: #include <vector> #include <iostream> using namespace std; struct Node { pu

我正在编写一个程序来查找链表中最后一个节点的第n个
。该程序生成正确的输出,但是,当我运行该程序时,我在
while(fast)
行中得到一个分段错误。当我使用print语句调试程序时,我注意到
while(fast)
即使
fast
指针为
NULL
(即
fast
超出列表末尾)也会被执行

关于如何修复分割错误有什么建议吗

这是我的密码:

#include <vector>
#include <iostream>
using namespace std;

struct Node {
public:
    int data;
    struct Node* next;
};

void insert(Node*& headPtr, int val) {
    Node* temp = new Node;
    temp->data = val;
    temp->next = headPtr;
    headPtr = temp;
}

Node* mth_to_last(Node* head, int m) {
    Node* fast = head;
    Node* slow = head;

    for(int i = 0; i < m; i++) {
        fast = fast->next;
    }

    while(fast) {
        fast = fast->next;
        slow = slow->next;
    }

    return slow;   
}

int main() {  
    Node* head;

    for(int i = 10; i >= 1; i--) {
        insert(head, i);
    }

    Node* res = mth_to_last(head, 4);
    cout << res->data << endl;
}
#包括
#包括
使用名称空间std;
结构节点{
公众:
int数据;
结构节点*下一步;
};
无效插入(节点*&headPtr,int val){
Node*temp=新节点;
温度->数据=val;
温度->下一步=水头;
headPtr=温度;
}
节点*第m个到最后一个(节点*头部,整数m){
节点*fast=头部;
节点*慢=头部;
for(int i=0;i下一步;
}
while(快速){
快速=快速->下一步;
慢=慢->下一步;
}
返回缓慢;
}
int main(){
节点*头;
对于(int i=10;i>=1;i--){
插入(标题i);
}
节点*res=第m个到最后一个(头部,4);
cout data是的

在使用()之前,您没有初始化
节点:

因此,
while
循环不会结束,因为
head
在开始时包含一些垃圾值

此外,您也没有初始化第一个节点的
next
指针(
head
)。现在,它不会导致问题,因为它没有被使用。但是,如果您确实开始使用它,它会导致问题,即更多UB。因此,您需要在构造函数中初始化它,例如:

struct Node {
    Node() : data{0}, next{nullptr} {}

    int data;
    Node* next;
};
或者,您可以这样使用:

struct Node {
    int   data {0};
    Node* next {nullptr};
};
请注意,
struct
的默认可见性为
public
,因此您无需提及,除非同一
struct
中存在
private
public
protected
访问说明符

也可以,在C++中,你可以这样做:

Node* next;
而不是

struct Node* next;
下面是一个具有上述更改的示例:

相关线程:

  • 是的

    在使用()之前,您没有初始化
    节点:

    因此,
    while
    循环不会结束,因为
    head
    在开始时包含一些垃圾值

    此外,您也没有初始化第一个节点的
    next
    指针(
    head
    )。现在,它不会导致问题,因为它没有被使用。但是,如果您确实开始使用它,它会导致问题,即更多UB。因此,您需要在构造函数中初始化它,例如:

    struct Node {
        Node() : data{0}, next{nullptr} {}
    
        int data;
        Node* next;
    };
    
    或者,您可以这样使用:

    struct Node {
        int   data {0};
        Node* next {nullptr};
    };
    
    请注意,
    struct
    的默认可见性为
    public
    ,因此您无需提及,除非同一
    struct
    中存在
    private
    public
    protected
    访问说明符

    也可以,在C++中,你可以这样做:

    Node* next;
    
    而不是

    struct Node* next;
    
    下面是一个具有上述更改的示例:

    相关线程:


    mth_to_last()的功能是什么?
    在语义上做什么?返回链接列表中最后一个节点的第n个。因此,如果列表是1->2->3->4,而n是2,它将返回3。
    mth_to_last()的功能是什么
    ?它在语义上做什么?返回链接列表中最后一个节点的第n个。因此,如果列表是1->2->3->4,而n是2,它将返回3。