简体   繁体   中英

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 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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