Access violation reading location 0xC0000005 C++ -
my add function has problem dereferencing first , first pointing nothing because of that. don't know how fix isn't null pointer.
struct node { int data; node *next; }; class linkedlist { node *first; node *last; int count; public: linkedlist() { first = null; last = null; count = 0; } void add(int item) { if (first == null) { first->data = item; last->data = item; last->next = null; first->next = last; count = 1; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; last->data = item; last->next = null; count ++; } }
you have lot of code in common between if
, else
.
if (first == null) { first->data = item; last->data = item; last->next = null; first->next = last; count = 1; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; last->data = item; last->next = null; count ++; }
in if
, increment count
0
1
. in else
, also increment it.
count
always getting incremented. don't need type twice.
if (first == null) { first->data = item; last->data = item; last->next = null; first->next = last; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; last->data = item; last->next = null; } count ++;
you're setting last->data
item
in both of them.
and you're setting last->next
null
in both of them.
if (first == null) { first->data = item; first->next = last; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; } last->data = item; last->next = null; count ++;
you forgot create new node
when it's first new node.
if (first == null) { node *newnode = new node; // added first = newnode; // added last = newnode; // added first->data = item; first->next = last; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; } last->data = item; last->next = null; count ++;
the first->data = item
in if
redundant. first
same last
there, , last->data = item
happening.
if (first == null) { node *newnode = new node; first = newnode; last = newnode; // removed first->next = last; } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; } last->data = item; last->next = null; count ++;
and since first
, newnode
have the same value in if
, can use variable names interchangeably.
if (first == null) { node *newnode = new node; first = newnode; // these 2 pointers equal! last = newnode; newnode->next = last; // (same pointer) } else { node *newnode = new node; newnode->data = last->data; newnode->next = last; } last->data = item; last->next = null; count ++;
now, almost everything in else
in if
. can all moved out.
node *newnode = new node; if (first == null) { first = newnode; last = newnode; } else { newnode->data = last->data; } newnode->next = last; last->data = item; last->next = null; count ++;
that code should more understandable now, too. lesson: don't repeat yourself. :)
Comments
Post a Comment