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