我之前已经实现了此类,但无法正常工作。我在enqueue(edge)方法中遇到错误。调试器说head不为空,但应该为空。谁能解释为什么?

这是代码:

class eList
{
private:
    class node
    {
    public:
        edge e;
        node * next;

        node(edge x)
        {
            next = NULL;
            e = x;
        }
    };

    node * head, *tail;

    public:
    eList()
    {
        head = NULL;
        tail = head;
    }


这是我得到错误的方法:

    void enqueue(edge component)
    {
        node * bby = new node(component);
        if (head == NULL)
        {
            head = bby;
            tail = head;
        }
        else
        {
            tail->next = bby;
            tail = bby;
        }
    }
};


如何使用此列表:

class edgeTable
{
private:
    //hash table conists of a table of lists
    eList * table;
    //size of table
    int capacity;

    //number of items in hash table
    int numItems;

    int createKey(edge e) {

        unsigned int k1 = e.start->address * 37;
        unsigned int k2 = e.end->address * 37;
        return k1+k2%capacity;
    }
    int createKey(int addss) { return addss%capacity; }

    void resize()
    {
        int oldCap = capacity;
        capacity = capacity * 2;
        edgeTable resized(capacity);

        for (int i = 0; i < oldCap;i++)
            resized.insert(table[i].strct());

        table = resized.table;
    }

    void insert(int key, edge e)
    {
        table[key].enqueue(e);
        numItems++;
    }

public:
    edgeTable()
    {
        capacity = 101;
        table = new eList[capacity];
        numItems = 0;
    }

    edgeTable(int cap)
    {
        capacity = cap;
        table = new  eList[capacity];
        numItems = 0;
    }

    void insert(edge e)
    {
        insert(createKey(e), e);
        if (numItems >= capacity / 2)
            resize();
    }


此类用于:

void addEdge(int x, int y, int w)
{
    vertex * u = findVertex(x);
    vertex * v = findVertex(y);

    edge e(u,v,w);
    u->edgeList.insert(e);
}


编辑:添加了补充代码。

最佳答案

我暂时无法添加评论,所以我来回答,就像评论一样。

void enqueue(edge component)确实没有问题,但是我认为您是void insert(edge e)的问题,尤其是insert(createKey(e), e);

createKey(e) createKey中不等于k1+k2%capacit
你想要这个吗?因为是键,它的意思是数组的索引,并且可能返回错误的索引!

抱歉,需要50/50来评论!

关于c++ - 我的链表方法有问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33823784/

10-11 23:02
查看更多