Hi,

I want to add a new node at 5th position in a single linked list in C++.Please help me with this..as am new to linked list.

Recommended Answers

All 3 Replies

Member Avatar for jencas

Do you mean std::list?

If you are writing a function to do the insert, keep in mind that you have to have a variable that knows where the items that go after the inserted item are located, so they will not be lost to the program

It's simple to do:

count =0;
listp = base;
while(listp = listp->next)
{
    count++;
    if (count==4) {
       temp = listp->next ;
       listp->next = node;
       node->next = temp;
    }
}

Of course that's not valid C and assumes stuff about the list structures, and needs more error checking...

Ruth

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.