删除元素并重新链接自定义链表(C ++)

时间:2016-02-17 12:26:37

标签: c++

我目前正在开发一个小程序,我们在其中创建一个自定义链表,可以接收从Shape类派生的对象。链接列表由包含指向下一个节点和形状对象的链接的节点构建。

自定义链接列表类(ShapeList)的标题如下:

class ShapeList {
public:

    ShapeList() : listStart(0) {
    }
    ShapeList(const ShapeList &shapes);

    ~ShapeList() {
        if (listStart != 0) delete listStart;
    }
    void add(const Shape& s);
    void remove(const Vertex& v);
    double area();
    void print();

private:
    Node * listStart;
};

节点的标题:

class Node {
public:
    Node(const Shape *v, Node * next): nextNode(next) {shapeInst = v->clone();}
//    Node (const Node &nod);
    ~Node() {if (shapeInst != 0) delete shapeInst;}
     Shape * getShape()  {return shapeInst;}
     Node * getNextNode()  {return nextNode;}
        void operator=(const Node * node){
        shapeInst = node->shapeInst->clone();
        nextNode = node->nextNode;
    }

private:
    Shape * shapeInst;
    Node * nextNode;
};

当我尝试从链接列表中删除元素时,问题就出现了。我似乎成功删除了对象,但删除后列表不会重新链接。

我试图为remove-function实现以下代码:

void ShapeList::remove(const Vertex& v) {

    Node * prev;

    Node* tmp = listStart;
    double x, y;

    if (listStart == NULL) {
        cout << "No objects present in the list!" << endl;
    } else {
        while (tmp != NULL) {

            x = tmp->getShape()->getX() - v.getXposition();
            y = tmp->getShape()->getY() - v.getYposition();

            if (x < 1 && y < 1) {

                if (tmp == listStart) {
                    listStart = tmp->getNextNode();
                    delete tmp;
                } else {
                    Node * next = tmp->getNextNode();
                    delete tmp;
                }

            } else {
                prev = tmp;
                tmp = tmp->getNextNode();
            }
        }
    }
}

当我尝试在删除后通过列表进行迭代时会崩溃。

当我将 Node * next = tmp-&gt; getNextNode(); 更改为 prev-&gt; getNextNode()= tmp-&gt; getNextNode(); (如http://www.cprogramming.com/snippets/source-code/singly-linked-list-insert-remove-add-count)中的删除功能所示

代码返回以下错误

ShapeList.cpp:69:41: error: lvalue required as left operand of assignment
                     prev->getNextNode() = tmp->getNextNode();
                                         ^

我错过了一些重要的事情,还是我只是盯着自己的代码?

0 个答案:

没有答案