1

After compiling -when the cmdl pops up- it doesn't terminate and waits just as awaiting input

#include <bits/stdc++.h>

using namespace std;

struct node{
    int data;
    node *next;
};

class LinkedList{
private:
    struct node *head;
    struct node *tail;
public:
    LinkedList(int val1,int val2){
        head->next = tail;
        head->data = val1;
        //tail->next = NULL;
        //tail->data = val2;
    }
    add(int val){
        struct node *n = new node;
        n->next = head->next;
        head->next = n;
        n->data = val;
    }
    display(){
        struct node *ptr = head;
        while(ptr->next!=NULL){
            cout<<ptr->data;
            ptr = ptr->next;
        }
    }
};

int main(){
    LinkedList l(1,3);
    for(int i = 0;i<5;i++) l.add(i);
    l.display();
}

What prevents the code from executing as expected? I tried some built-in functions to test the code however none of them responded to the calls and had effect.

Mat
  • 202,337
  • 40
  • 393
  • 406
emirhan422
  • 87
  • 5

1 Answers1

2

I get an access violation when running this code.

adding

head = new node;

at the beginning of your constructor fixes that.

I would also explicitly initialize head and tail to null like this

private:
     struct node *head = NULL;
     struct node *tail = NULL;

Otherwise they're filled with garbage values and you'll potentially get an infinite loop in your display code.

iverss
  • 106
  • 7
  • 1
    Also worth asking "Why is my constructor adding a node?" Having to supply a an item to the constructor will make this liked list less useful as you now must know what the first item will be when creating the node, and this is a luxury you often do not have. – user4581301 Mar 16 '20 at 15:17