I have searched for and read through over 50 examples of linked lists. I can barely make heads or tails out of them. Some are in C, some are in Java, some use templates, most only discuss theory and display flowcharts but have few explained examples. I need serious help!
Below is the one example that I can half way understand well enough to even start asking questions about linked lists.
#include "../../std_lib_facilities.h"
struct Node {
int num;
Node *link;
} *p;
int main()
{
Node *root;
root = new Node;
root->num = 5;
root->link = p;
p = root;
Node *q;
for (q = p; q != NULL; q = q->link) {
cout << q->num << endl;
}
keep_window_open();
return 0;
}
Why is "struct" being used instead of "class" to introduce the linked list nodes? Is it a preference for not having to declare the lines public if "class" is used?
I understand that "num" is the data value held in the node and that "link" is the pointer to the next node. What is "p"? The author explained that "link" points to "p" and that "p" points to the next node. I don't follow that logic. What is the need to create a pointer that is outside the list node?
I understand the creation of the pointer "root" and setting its value equal to a new list node. I understand the setting of the data value for the new node to 5. I understand that the old pointer value needs to be set to the address of the new node and that the pointer value in the new node needs to be set to NULL. I do NOT follow how setting the value of "link" equal to "pP and having "root" point to "link" and then having "p" take on the value of "root" accomplishes that. It seems to me that "root" ends up pointing back at itself.
For displaying the data contents of each node, I don't understand why a third pointer "q" needs to be created. Why can't "p" accomplish by itself what "q" does? ie.
for (p != NULL; p = p->link) {cout << p->num << endl;}
?
I did some experimenting. The program still compiles and runs correctly after changing "struct" to "class" with public. So I guess that answers my first question. I also eliminated "q" in the display lines. The progran compiled and ran but did not display the value 5. So that pointer "q" is needed, but I don't understand why.
Thanks in advance for your help.