简体   繁体   English

分段错误 - 链表实现

[英]Segmentation fault - Linked list implementation

I am getting segmentation fault in my code for implementation of linked list.我在执行链表的代码中遇到分段错误。 Any help is appreciated.任何帮助表示赞赏。 Thanks.谢谢。 I have purposely added struct methods in here.我特意在这里添加了 struct 方法。

struct node{
    int data;
    node *next;

    node(int data){
        this->data = data;
        this->next = NULL;
    }

    node(int data, node *next){
        this->data = data;
        this->next = next;
    }
    int getData(){
        return data;
    }
    node* getNextNode(){
        return next;
    }
};

class LinkedList {
    private: 
        node *head,*tail;
    public:
        linked_list(){
            head=NULL;
            tail=NULL;
        }
        void addNode(int data){
            node *temp = new node(data);
            if(head==NULL){
                head = temp;
                tail = temp;
            }
            else {
                tail->next = temp;
                tail = temp;
            }
        }
        void display(){
            node *temp;
            temp = head;
            cout<<"PRINTING LINKED LIST"<<endl; 
            while(temp!=NULL){
                cout<<temp->getData()<<" ";
                temp = temp->getNextNode();
            }
        }

};

I get segmentation fault when I invoke the following code :调用以下代码时出现分段错误:

LinkedList myLinkedList;
myLinkedList.addNode(1);
myLinkedList.addNode(2);
myLinkedList.display();

Stack overflow is asking for more details, for me to post this question.堆栈溢出要求提供更多详细信息,以便我发布此问题。 Putting in some gibberish, please ignore following part : Lyrics to 'Humpty Dumpty' by Songs For Children: Humpty Dumpty sat on a wall, Humpty Dumpty had a great fall All the king's horses and all the king's men.胡言乱语,请忽略以下部分: 儿童歌曲“矮胖”的歌词:矮胖坐在墙上,矮胖摔倒了所有国王的马匹和所有国王的手下。

The problem is here问题就在这里

class LinkedList {
    private: 
        node *head,*tail;
    public:
        linked_list() {
            head=NULL;
            tail=NULL;
        }

linked_list is not the constructor for LinkedList because the spelling is different. linked_list不是LinkedList的构造函数,因为拼写不同。 Obviously it should be like this明明应该是这样

class LinkedList {
    private: 
        node *head,*tail;
    public:
        LinkedList() {
            head=NULL;
            tail=NULL;
        }

Now the code you posted should not have compiled, or at least it should have produced compiler warning messages.现在你发布的代码不应该被编译,或者至少它应该产生编译器警告消息。 Always pay attention to your compiler's warning messages.始终注意编译器的警告消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM