袋子数据结构的增量计数器

Increment counter for bag data structure

本文关键字:计数器 数据结构      更新时间:2023-10-16

所以我创建了一个袋子数据结构,并且我试图在每次插入字符串的相同实例时增加计数器,但由于某种原因,即使我输入了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上面提到的,您仍然存在内存泄漏。我还要补充一点,始终存储字符串的小写版本可能比每次都重新计算要好。