袋子数据结构的增量计数器
Increment counter for bag data structure
所以我创建了一个袋子数据结构,并且我试图在每次插入字符串的相同实例时增加计数器,但由于某种原因,即使我输入了10个相同的字符串,我的计数器也从未增加。建议吗?
struct BagNode
{
string dataValue;
int dataCount;
BagNode * next;
};
class Bag{
private:
BagNode * head;
public:
Bag()
{
head = NULL;
//curr = NULL;
}
void insert(string v)
{
if(head == NULL){ //empty list
head = new BagNode;
head->dataValue = v;
head->next = NULL;
}
else
{
BagNode * n = new BagNode; // new node
n->dataValue = v;
n->dataCount = 0;
BagNode * current = head; //for traversal
//current = head;
if(isSame(current->dataValue,v))
{
n->dataCount+= 1;
}
else
{
if(!isBefore(current->dataValue, v)) //new head
{
n->next = head;
head = n;
}
else{ //mid and tail insert
while(current->next && isBefore(current->next->dataValue,v))
{
current = current->next;
}
n->next = current->next;
current->next = n;
}
}
}
}
bool isSame(string a, string b)
{
transform(a.begin(), a.end(), a.begin(), ::tolower);
transform(b.begin(), b.end(), b.begin(), ::tolower);
if(a == b) {
return true;
}
else {
return false;
}
}
void traverse()
{
BagNode * current;
current = head;
while(current)
{
output << current->dataValue << " (" << current->dataCount << ")" << " ";
current = current->next;
}
cout << endl;
}
您正在检查是否应该对列表的第一个元素进行自增,否则您只需遍历列表以确定在何处插入新节点。请记住,您从未实际检查过其他节点是否包含您应该查找的值。你只需要修复它。
正如Sam上面提到的,您仍然存在内存泄漏。我还要补充一点,始终存储字符串的小写版本可能比每次都重新计算要好。
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 袋子数据结构的增量计数器