I have this Homework Problem that I can't figure out. Here it is:
Revise 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.
Here is the code i have so far...
//Created by Michael R. Martin
// assignment 11 problem 8
#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 = d;
newlink->next = first;
first = newlink;
}
/////////////////////////////////////////////////////////
void linklist::display()
{
link* current = first;
while(current !=NULL)
{
cout<< current->data<<endl;
current = current->next;
}
}
///////////////////////////////////////////////////////
int main()
{
linklist li;
You pretty much already have the functionality that you need made, you just need to arrange it right. You need to get to the end of the list, and that's exactly what your while loop in display does. So put that in additem (get rid of the outputting part), and then create a new node and assign it similar to how additem already does.
void linklist::additem(int d)
{
link *current = first;
while (current != NULL)
current = current->next; // will continue until current is at the end
// make new link and assign values;
}
Please use code tags in the future (highlight your code and click the "<>" under Format).
I feel incredibly dumb asking for help. Logically its simple but when it comes to the code and pointers...it is all very new to me and confusing as hell.
Don't feel bad; pointers and linked lists are tough. You don't need to touch anything in your other functions. I'll just finish the function and try to explain it:
void linklist::additem(int d)
{
link* newlink = new link; // new node to be added
newlink->data = d;
newlink->next = NULL;
// At this point we have our new node, ready to be added
// But now we have to find its home: the end of the linked list
link *current = first;
while (current != NULL && current->next != NULL)
{
current = current->next; // will continue until current is at the last node
}
// Now current is at the last node of the list, and all we need to do now is point it at the node we made
current->next = newlink; // all done
}
Ok, I think that's right, but I haven't tested it at all.