我有以下List类:
typedef int Elem; // list base element type
class NodeList { // node-based list
private:
struct Node { // a node of the list
Elem elem; // element value
Node* prev; // previous in list
Node* next; // next in list
};
public:
class Iterator { // an iterator for the list
public:
Elem& operator*(); // reference to the element
bool operator==(const Iterator& p) const; // compare positions
bool operator!=(const Iterator& p) const;
Iterator& operator++(); // move to next position
Iterator& operator--(); // move to previous position
friend class NodeList; // give NodeList access
private:
Node* v; // pointer to the node
Iterator(Node* u); // create from node
};
public:
NodeList(); // default constructor
int size() const; // list size
bool empty() const; // is the list empty?
Iterator begin() const; // beginning position
Iterator end() const; // (just beyond) last position
void insertFront(const Elem& e); // insert at front
void insertBack(const Elem& e); // insert at rear
void insert(const Iterator& p, const Elem& e); // insert e before p
void eraseFront(); // remove first
void eraseBack(); // remove last
void erase(const Iterator& p); // remove p
private: // data members
int n; // number of items
Node* header; // head-of-list sentinel
Node* trailer; // tail-of-list sentinel
};
我的代码不进行任何检查以确定给定位置(迭代器对象)是否实际上是特定列表的成员。例如,如果 p 是列表S中的位置,并且我在另一个列表T上调用T.insert(p,e),那么我实际上是在p之前将元素添加到S.如何更改我的NodeList实现以禁止这种滥用?
答案 0 :(得分:1)
这意味着有点内存开销,但是如果你将每个列表的头部存储在所有节点中,你可以检查头是否相同,那么它可能是相同的列表。
或者如果您更喜欢CPU开销而不是内存开销,请遍历prev-links以找到两个列表的头部并按上述方式进行比较。
所以这取决于你喜欢哪种开销。