Monday, July 27, 2009

C++ Node Help?

So this program is supposed to take in 2 numbers one is the data and the second is used as a positioner to position where the data will be placed in the list. However I am a bit stuck and and having some programmers block can someone look over this with fresh eyes?





Thanks!





// 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

C++ Node Help?
One thing I see is that you're setting head to point to itself. on that head-%26gt;link = head line. I think you need newNode-%26gt;link = head instead.





Ditto for end-%26gt;link in the next if-clause.





Also, what do you do if the new node isn't at one end of the list or the other, in other words, somewhere in the middle?





And what if the new node actually matches one of the ends Your data may be structured here so this won't happen, but in the real world, you'd have to take this into account.





Hope that helps.
Reply:There's almost no point having an end pointer unless you have reverse links in the structure too.





This part needs some fixing:





else if(newNode-%26gt;sorter %26lt; head-%26gt;sorter)


{


// head-%26gt;link = head; // now its pointing to itself


newNode-%26gt;link = head; // this is the right way


head = newNode;


}


else if (newNode-%26gt;sorter %26gt; end-%26gt;sorter)


{


// end-%26gt;link = end; // now its pointing to itself


end-%26gt;link = newNode; // this is the right way


end = newNode;


}





You probably want to insert newNode into the middle of the list if it doesn't go at the head or end. If you don't do anything with newNode, it will just be lost in space and be a memory leak.





After leaving the while loop, you should check the head and end pointers before using them. If the user entered -99 for the first one, there will be an empty list.


No comments:

Post a Comment