Beginner: Pointers error:Access violation...

/* Exercise 8: Revise the additem() member function from the linklist program
so that it adds the item at the end of the list, rather than the beginning.
This will cause the first item inserted to be the first item displayed, so the
output of the program will be: 25 36 49 64 To add the item, you'll need to follow
the chain of pointers to the end of the list, then change the last link to point
to the new link. */

#include <iostream>
using namespace std;

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

class linklist {
private:
link* first;
public:
linklist() { first = NULL; }
void additem(int d);
void display();
};

void linklist::additem(int d) {
link* newlink = new link;
newlink->data = first->data;
newlink -> next = first;
newlink -> data = d;

first = newlink;
}

void linklist::display() {
link* current = first;
while(current != NULL ) {
cout << current -> data << endl;
current = current -> next;
}
}

int main() {
linklist li;
li.additem(25);
li.additem(36);
li.additem(49);
li.additem(64);

li.display();
system("pause");
return 0;
}

however @ newlink->data = first->data; i think i may have a memory leak, nd i'm too in experienced to fix it...Thank you

1
2
3
4
5
6
7
8
void linklist::additem(int d) {
link* newlink = new link;
newlink->data = first->data; //<<==Get rid of this - it's wrong
newlink -> next = first;
newlink -> data = d;

first = newlink;
}
Last edited on
 
newlink->data = first->data;


This should give a segmentation fault, if 'first' is set to NULL. (and it certainly is, if the list is empty)
Just remove this line, but it does not solve your excercise.

Greatings, Maikel
void linklist::additem(int d)
{
link* newlink = new link;
newlink->data = d;
newlink->next = NULL;
link* current = first;
while(current != NULL )
{
current = current -> next;
}
current->next = newlink;
}

This is for adding the node to the end of the list .
Hope this helps.



}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void linklist::additem(int d)
{
link* newlink = new link;
newlink->data = d;
newlink->next = NULL;
link* current = first;
while(current != NULL )
{
current = current -> next;
}
current->next = newlink;
}

}


This is for adding the node to the end of the list .
Hope this helps.
additem method should be as follow:
1
2
3
4
5
6
7
8
9
10
11
12
void linklist::additem(int d) {
  link* newlink = new link;
  newlink->data = d;
  newlink->next = NULL;
  if (first != NULL) {
    link* current = first;
    while(current->next != NULL) 
      current = current->next;
    current->next = newlink;
  } else
    first = newlink; //very first item	
}
Last edited on
yes you are right serge ... thanks
Thanks to you both (serge and bluecoder) you buoth helped me understand my error and why i got it a little bit more.
Topic archived. No new replies allowed.