Skip to content
This repository was archived by the owner on Jan 20, 2025. It is now read-only.

Commit 26563e6

Browse files
committed
Make LinkedList iterator safe against removal of cur item
1 parent 1d46269 commit 26563e6

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/StringArray.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,19 @@ class LinkedList {
4747

4848
class Iterator {
4949
ItemType* _node;
50+
ItemType* _nextNode = nullptr;
5051
public:
51-
Iterator(ItemType* current = nullptr) : _node(current) {}
52-
Iterator(const Iterator& i) : _node(i._node) {}
53-
Iterator& operator ++() { _node = _node->next; return *this; }
52+
Iterator(ItemType* current = nullptr) : _node(current) {
53+
_nextNode = _node != nullptr ? _node->next : nullptr;
54+
}
55+
Iterator(const Iterator& i) : _node(i._node) {
56+
_nextNode = _node != nullptr ? _node->next : nullptr;
57+
}
58+
Iterator& operator ++() {
59+
_node = _nextNode;
60+
_nextNode = _node != nullptr ? _node->next : nullptr;
61+
return *this;
62+
}
5463
bool operator != (const Iterator& i) const { return _node != i._node; }
5564
const T& operator * () const { return _node->value(); }
5665
const T* operator -> () const { return &_node->value(); }

0 commit comments

Comments
 (0)