Reputation: 97
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.
Upvotes: 1
Views: 106
Reputation: 106
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.
Upvotes: 2