Jamin2112
- 973
- 12
I'm making a generic linked list class. For reference, firstNodePtr and lastNodePtr are pointers to the nodes at the beginning and end of the list. I'm trying to make a function that removes duplicate elements, which in turn calls a function for deleting a particular node. I think it does what I want (or does it?) but I also feel like this is overly complicated and I could simplify it somehow. Thoughts?
Code:
template <class T> void List<T>::remove_duplicates() {
std::set<T> thisSet;
node* curNodePtr = firstNodePtr;
while (curNodePtr) {
if (!thisSet.count(curNodePtr->val)) {
thisSet.insert(curNodePtr->val);
curNodePtr = curNodePtr->next;
} else {
node* curNodePtrCopy = curNodePtr;
curNodePtr = curNodePtr->next;
delete curNodePtrCopy;
}
}
}
template <class T> void List<T>::remove_node(node* thisNodePtr) {
if (thisNodePtr == firstNodePtr) {
firstNodePtr = firstNodePtr->next;
} else {
node* prevNodePtr = firstNodePtr;
while (prevNodePtr->next != thisNodePtr)
prevNodePtr = prevNodePtr->next;
prevNodePtr->next = thisNodePtr->next;
if (thisNodePtr == lastNodePtr)
lastNodePtr = prevNodePtr;
}
delete thisNodePtr;
}