The requirement is an input function that returns a Node* to the root of a linked list that input creates from the user’s input.
Like:
Node *input()
{
Node *root; //not yet allocated
while(1)
{
//take in numbers from the user and correspondingly add them
//to the linked list and quit when anything else is entered
if(input character is a number)
{
//allocate memory to a fresh pointer and push the number to it
//and add this new Node to the LL
}
}
return root;
}
-> There is the solution of pre-allocating memory to root and pushing the 1st number to it before the while loop body. But here, if the user won’t enter anything, that must deleted right away.
-> Also, there is a possible way of checking if root is NULL in the while loop, and if it is, allocating memory , so that it happens only once.
But I would like to know if there is a solution that will eliminate that odd situation arising from the root of the LL.
-> Maybe I could keep a dummy node at the 1st that doesn’t hold any values.
But apart from that?
If there is a better method of doing the whole thing, please suggest it.
You can do something like:
And you’re done, no special case required for the first element. The end of list is indicated by a null
nextpointer.If you want the list to be in insertion order, without traversing the whole list each time, you could:
No special-case allocation, but special-case assignments.