It is clear that in the void additem(int d) method we can access the fields of the link structure via a pointer to the structure object as follows:
newlink->data = d; newlink->next = first; Then how do we access these very fields of the structure through the current pointer in the class method, if this pointer does not point to the structure from the very beginning:
link* current = first; while (current) { cout << current->data << endl; current = current->next; } ???
Code:
class linklist { struct link { int data; link* next; }; 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) { cout << current->data << endl; current = current->next; } } int main() { setlocale(LC_ALL, "rus"); linklist li; li.additem(23); li.additem(9); li.additem(11); li.additem(0); li.display(); cout << endl; system("pause"); return 0; }
current- in your case,iis a loop variable. You have a cycle to the next, while the next exists. In principle,for (i=0;i<n;i++)can be written asi=0(first)while (i< n) { i=i+1}instead ofi=i+1you havecurrent =current->next;- nick_n_acurrentpointer, ifcurrentdoes not point to the structure object? - Artem Aleksandrovich