Hey Lynux-Penguin, this can be done a lot better
Code:
int createNode(int id, nodeptr &nde)
{
if(nde)
return 1;
nde = new node;
nde->id = id;
nde->next = NULL;
return 0;
}
That relies on the calling function to do several things... yuck. I know that you didn't write that as a class, but you could have, and really, maybe should have. Anyway, this code does the same thing, but is better.
Code:
int createNode(node *headnode)
{
node *current = *headnode;
int id=0;
if(current)
{
while (current->next) //keep going until current is last node
{
current=current->next;
id++;
}
current->next=new node;
if (current->next)
{
current->next->next=NULL;
current->next->id=id; //I don't know what you're using id for
//but I left it
return 0;
}
return 1; //failure
}
If you stick the linked list functions together in a class, it becomes even better. Your next pointers are safe (private members), the list can allocate new nodes for itself, delete portions of itself, and just in general protect itself and clean up when you're done with it. If you decide to program a linked list class, the "this" keyword will be of much use to you (at least it was to me). Here's some code from my llist class.
Code:
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
class llist
{
public:
int adddata(unsigned char add);
llist(void);
~llist(void);
void printlist();
private:
unsigned char data;
llist *next;
};
int llist::adddata(unsigned char add)
{
llist *current = this; //this is a pointer to this instance of the class
while (current->next) //move current to the last llist in the list
current = current->next;
current->next = new llist; //create a new llist at the end of the list
if (current->next) //memory allocation succeeded
{
current->next->data=add; //store add in the new llist
return EXIT_SUCCESS;
}
else //memory allocation failed
return EXIT_FAILURE;
}
llist::llist()
{
next=NULL;
data = 0;
}
llist::~llist()
{
if (next) //use recursion to delete all the llists after this one
delete next;
}
void llist::printlist()
{
llist *current = this;
while (current)
{
cout<<current->data<<endl; //display current node's data
current=current->next; //move to next node
} //rinse and repeat
}
edit: smileys in my code, lol