Doubly LinkedList... Insert after function

this function is not working... can any body help me with this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  template <class T>
void LinkedList<T>::insertAfter(T toInsert, T afterWhat)
{
	ListItem<T> *newOne = new ListItem<T>(toInsert);
	ListItem<T> *current, *cur_next;
	
	current=head;
	
	while(current->next != NULL )
	{
		current = current -> next;
	
		if(current->value==afterWhat)
		{
			cur_next=current->next;
			newOne->next=cur_next;
			cur_next->prev= newOne;
			newOne->prev=current;
			current->next=newone;
		}
	}				

}
At line 11 you're skipping to the next item before doing the check. That means that if you want to insert after the first item, you won't find it. Worse, it could set current to nullptr which means the line 13 will result in undefined behavior and probably will crash the program.

I like to use the for construct with loops. It lets you separate the loop logic from the logic that gets executed within each iteration:
1
2
for (current=head; current; current = current->next) {
...


At line 17, you need to check if cur_next is NULL first, assuming that this is not a circular list.
Topic archived. No new replies allowed.