Answer the question
In order to leave comments, you need to log in
How does a linked list work?
I don’t understand a little what exactly the program code is doing at this moment.
template<class TYPE>
struct link
{
TYPE data;
link* next;
};
template<class TYPE>
class linklist
{
private:
link<TYPE>* first;
public:
linklist(){ first = NULL; }
void additem(TYPE d);
void display() const;
};
template<class TYPE>
void linklist<TYPE>::additem(TYPE d)
{
link<TYPE>* newlink = new link<TYPE>;
newlink->data = d;
newlink->next = first;
first = newlink;
}
template<class TYPE>
void linklist<TYPE>::display() const
{
link<TYPE>* current = first;
while (current != NULL)
{
cout << endl << current->data;
current = current->next;
}
}
int main(int argc, char**argv)
{
setlocale(0, "");
linklist<double> ld;
ld.additem(151.3);
ld.additem(121.3);
ld.additem(531.3);
ld.display();
linklist<char> lch;
lch.additem('a');
lch.additem('b');
lch.additem('c');
lch.display();
_getch();
return 0;
}
template<class TYPE>
void linklist<TYPE>::additem(TYPE d)
{
link<TYPE>* newlink = new link<TYPE>;
newlink->data = d;
newlink->next = first; // вот здесь не пойму, что именно мы записываем в next
first = newlink; // и здесь не пойму, что именно мы присваиваем first
}
/////////////////////////////////////////////
template<class TYPE>
void linklist<TYPE>::display() const
{
link<TYPE>* current = first; // что именно мы записываем в current?
while (current != NULL)
{
cout << endl << current->data;
current = current->next; // и тут тот же вопрос :/
}
}
Answer the question
In order to leave comments, you need to log in
The answer to all your questions is pointers . Answering within the framework of a toaster the question of what pointers are is a thankless task, IMHO.
brief description:
1) first stores a pointer but the top of the list (first = newlink;) here we create a new element and store a pointer to it.
2) newlink->next = first; - the previous top of the list is stored here
3) link* current = first; here we take the top of the list and just copy it to another variable
4) current = current->next; - from paragraph 2) it is clear that a pointer to the previous vertex is stored here, in other words, to the previous element.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question