hey,
i've been trying to insert the element in the linked list, but I don't understand why the element is inserted at some other position i.e. it is not inserted at the position which i pass.
is there any error in the insert function?

template <class T>
void insert ( int pos , T y)  // passing position of element and element to be inserted
{
    int c = 0;
    node<T> *tmp;
    node<T> *curr= new node;
    while ( c < pos )
    {
        tmp = tmp -> next;
        c++;
    }
    curr -> item = y;
    curr -> next = tmp -> next;
    tmp -> next = curr;
}

1)Did you forget to initilise tmp? Where does it start from?
2)You need to check whether or not your linked list is empty. If it is empty, what would you do?
3)If it is not empty, is the given index within the range? If it is out of range, what would you do?

the snippet i've posted is just a part of program. Actually, I want to add an element to a linked list which is NOT empty.

Did you forget to initilise tmp? Where does it start from?

this could be the problem. I didn't initialise tmp. But while programming in C, I never faced any problem regarding the initialization of tmp??

OK, if you ask a question and posted code portion, please at least show a completed portion. Or at least list your assumption of whatever you assume because other people may make different assumption from what you and only you know.

Here is what I would at least hope to see...

node<T> *tmp=head_node;  // see what I am talking about initialization?
// or you could do
// node<T> *tmp;
// tmp = head_node;

Also, if a linked list is not empty, what would you deal with an invalid index such as negative value?

Another problem is that if the given value is out of range, what do you think would happen when tmp = tmp->next and because tmp becomes null?

Oh, and I expect that given position 3 means inserting into position of index 3 of index-zero, correct?

sorry.. I thought you wanted me to initialize tmp to NULL first..
forgot to initialize the tmp to head. I forgot to write that line
problem solved..
its just a basic approach to check my code now.. i'l make the necessary changes :)
thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.