This is a code for singly linked list, I wanted the value of 'head' to point to the head of the linked list. And it seems that i have coded in that fashion only, but the 'head' changes and goes to the tail, i dont know why. I even tried deleting all the 'tail' terms, but its the same result.
You're causing undefined behavior here, because you assign head and tail the memory address of something that won't exist anymore once the function returns.
Anyways: I suggest you to delete all of what you've written so far and start over.
No, that won't work either. That way, you have to keep the list in the same scope in which the nodes are created, which isn't very likely to be what you want (well I guess this is a homework so you probably don't care, but this would mean that the list is completely unusable).
I din't understand what you are saying here, could you please elaborate?
As per the code, yes, i will have to create the node, and add it in the list in the same scope in which i declare the nodes.
But,
Then i can go ahead and send that SLL to other functions and use it. Because you said, i made a test function where the scope of the nodes is not there, but still the code works fine.
What if another function needs to add a node to the list? Since you are allocating on the stack and just copying the address you will run into problems. I usually keep the node class internal to the list and just add the data. But you're method could work if you create a node and just copy the data (in addnode()).
int main()
{
//Moved to outer scope..
SLL mySLL;
{
node myVector[4];
for(int i = 0; i<4; i++)
{
myVector[i].data = i+1;
}
mySLL.addNode(myVector[0]);
mySLL.addNode(myVector[1]);
mySLL.addNode(myVector[2]);
}
//BOOOM, what does ->data reference? myVector has been deconstructed when it
//left scope...
cout << mySLL.head->data << endl;
return 0;
}
It doesn't matter if you pass by reference or by value the way that addnode is implemented it does not own the memory it references. To properly do this, you allocate memory for a node and add the newly allocated memory, then your node pointers will own the memory. When you are done, you have to free that memory.