Ok guys I updated my code right now whats happening is Im getting an infinite loop when I try to print the contents of the list out.
//in a header file
#ifndef NODE_H
#define NODE_H
#include %26lt;iostream%26gt;
using namespace std;
struct Node
{
int data;
int sorter;
Node *link;
};
#endif
*UPDATED* C++ Node Help?
I have suspicions about this code:
else
newNode-%26gt;link = head-%26gt;link;
head-%26gt;link = newNode;
For one thing, only that assignment to newNode-%26gt;link falls under the else. The head-%26gt;link will be executed after ALL cases. That doesn't sound right to me.
For another, you're not putting the new node in its proper place. You have to have at least a search loop for that, don't you?
Also, on general principles, I wouldn't use an Assert to test for an allocation failure in new. Asserts may be active only while debugging, while an out-of-memory condition could occur in an operational application.
Reply:First, before telling you WHY your printing is going to infinite loop, let me tell you that your code has a bug in it. The bug is where you are trying to insert the "newNode" in the case when newNode's "sorter" value is neither less than the head's nor more than the end's - rather it is in between the two.
In that case, you are trying to insert it right after head.
But that does not gurantee that the nodes will be properly sorted by "sorter". Say your head has sorter = 4, end has sorter = 8. Then, for the 3rd node, user enters 5. You correctly put it after head, so now the sequance is
4 - 5 - 8
Next, for teh 4th node, user enter 6. You will put it after the head, too, and the sequence bcomes
4 - 6 - 5 - 8
and that whacks up your sorting!
Now back to your original question: In the final "else" statement you are using, try using brackets around the 2 statements following that else :-)
Finally, please cultivate the habit of writing delete for every new. It will help you in the long run.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment