c++ remove linked list

This is my current code. The code is to remove the element in the list "head" that is "e". The code works if there is only one element in the list but if there are more than 1 element in the list, it doesn't work. The function should return true if there is an element that equals "e" and then it removes it and false if no element equals "e".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool StringLinkedList::remove(const std::string& e){
	StringNode* current = head;
	int i = 0; 
	if (current == NULL)
		return false;
	while (current != NULL){
		if (current->elem == e){
			current = current->next;
			head = head->next;
			i++;
		}
		else{
			current = current->next;
		}
	}
	if (i > 0){
		n--;
		return true;
	}
	else{
		return false;
	}
	
}
Last edited on
To delete a node, you will need access to the node before the victim node in the linked list. For example, if you want to delete the current node,

1
2
3
4
previous->next = current->next;

//and don't forget to release the memory.
delete( current );
Registered users can post here. Sign in or register to post.