簡體   English   中英

singleLinkedlist c++ 分段錯誤核心轉儲

[英]singleLinkedlist c++ segmentation fault core dumped

我正在嘗試創建一個單鏈表,但上面的代碼給出了一個錯誤:segmentation fault core dumped。 我在單鏈表中插入元素 5、9、12 並顯示列表。 首先,我創建一個節點,然后使用所有方法創建 class 單鏈表。 我仍在努力學習基礎知識。

#include <iostream>
using namespace std;
class Node
{
    public:
    int data;
    Node* next;
    Node()
    {
    }
    Node(int element)
    {
        data = element;
        next=NULL;
    }
    Node(int element, Node* link)
    {
        data = element;
        next = link;
    }
};
class SingleLinkedList
{
    public:
    Node* head;
    int listsize = 0;
    Node* curr;
    bool isempty() 
    {
        return head==NULL;
    }
    void Insert(int data)
    {
        Node* new_node = new Node(data);
        if(isempty())
        {
             head = new_node;
             listsize++;
             return;
        }
        curr = head;
        while(curr->next!=NULL)
        {
            curr->next=curr;
        }
        curr->next=new_node;
        listsize++;
        
    }
    void display()
    {
        curr = head;
        while(curr!=NULL)
        {
            cout<<curr->data<<"-->";
            curr=curr->next;
        }
    }
    
};
int main()
{
    SingleLinkedList l1;
    l1.Insert(5);
    l1.Insert(9);
    l1.Insert(12);
    l1.display();
}

嘗試改變:

 while (curr->next != NULL)
 {
     curr->next = curr;
 }

至:

while (curr->next != NULL)
 {
     curr = curr->next;
 }

為您在進行節點插入時列出遍歷以避免無限循環

指針head未初始化。 它的值不保證為nullptr 因此,您的代碼是 UB,因為列表中的第一個插入將調用isempty() ,它正在使用這個未初始化的指針。

完成后,還要考慮Anon的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM