Reputation: 13123
Lets say I have a linked list which contains the following:
1, 2, 4, 5, 6, 2, 3, 2
now lets say I wish to convert this to:
1, 10, 2, 4, 5, 6, 10, 2, 3, 10, 2
i.e. insert 10 before all 2's.
How should I do this?
Upvotes: 3
Views: 5580
Reputation: 1929
while(item != NULL)
{
if(item->intval == 2)
{
Item *newitem = (Item *) malloc(sizeof(Item));
newitem->intval = 10;
prev->next = newitem;
newitem->next = item;
}
prev = item;
item = item->next;
}
If you made your own linked list. Also off the top of my head, and c style.
Upvotes: -1
Reputation: 429
create a structure with node and info like
struct test{
int info;
int *node;
}
you can refer them as test->info and test->node
now try something like this .
while(end_of_list){
list[index]=2;
create a new structure object(new_struct) .
new_struct->info=10;
new_struct->node=node_containing_2.
previous_node_to_2->node=new_struct.
}
Upvotes: 0
Reputation: 409166
Maybe something like this:
auto it = l.begin();
while ((it = std::find(it, l.end(), 2)) != l.end())
{
it = l.insert(it, 10);
std::advance(it, 2);
}
Upvotes: 1
Reputation: 8027
Off the top of my head
for (std::list<int>::iterator i = l.begin(); i != l.end(); ++i)
if (*i == 2)
l.insert(i, 10);
Simple enough. You don't need to worry about iterator invalidation because insert
on a std::list
does not invalidate any iterators. It's one of the advantages of using std::list
.
Upvotes: 9