So I have a linked list with multiple elements in each list that are read in from a file. So far I have got the list to store all the info. But my problem is I don't know how to start from the beginning of a list to print them all out.
The temp node that I declared in the main file was my attempt at doing this but it would only print out the last and first element in the list. How can I fix this?
Thanks!
R 150 1.00
R 130 2.00
S 145
R 50 2.50
S 75
S 180
R 50 4.00
R 30 5.00
R 40 5.50
P 30
S 50
S 30
R 50 6.00
R 265 10.00
S 60
P 50
S 100
S 70
S 175
R 40 14.00
R 75 15.00
S 110
R 30 16.00
R 40 18.00
c-style example, see if my changes make sense. Also, because you're using (!fin.eof()) as your test, you are going to have that one bad node at the end of your list.
coder777, I see what you mean and that probably explains why it would only print one element in the list.
tipaye, your corrections worked and I follow almost everything you did. But I don't understand why in the first while loop you had to add newNode->next = NULL; a second time. Additionally, why would we need the next two lines
1 2
prev->next = newNode;
prev = newNode;
if we already established that the node points to the first node with node *prev = firstNode; and newNode->head = prev->head;?
Hi,
You're quite right, one of the newNode->next = NULL; doesn't need to be repeated, that's a copy and paste error on my part :-)
Before the loop, node *prev = firstNode; and newNode->head = prev->head;
prev is going to be used as a pointer to the previous node, this will change every time we add a new node to the list, as you can see in the first loop. It starts off pointing to the first node, because the first node has no priors and will be the previous node for the next node we add. prev->next = newNode;
The "next" of the previous node is originally NULL, as it was the last node. Now we're adding a new node so we update it to point at the new node. This is how we link them, and where the "linked" in linked list comes from. prev = newNode;
Well, the new node we've just created will be the prev node for the next node we create. We have to keep moving on!
Whenever we add a new node, we update it's head pointer to whatever the prev node says head is. I understand you might expect this to be newNode->head = firstNode; instead of newNode->head = prev->head;
The idea behind the second one is to illustrate that we don't need to keep track of firstNode as a separate variable. The list can be increased from a different scope without explicit knowledge of firstNode.
In fact, we don't need both prev and firstNode, I just thought it would make things clearer. You could delete the definition of prev on line 30, and change every occurence of firstNode to prev, and the code would work just the same. I think.
Hope this helps...