此代码来自"数据结构"本书由Micheal T.Goodrigh撰写。我自己学习,所以我没有人为我解释这段代码:
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
};
我很困惑如何使用insert()
方法。当iteretor在其类中并且Node
是私有的时,如何将迭代器传递给它?
int main () {
NodeList Nl;
N1.insert(p,5) // How to create this p iterator and pass it to insert?
return 0;
}
答案 0 :(得分:1)
begin()
方法将Iterator
返回到列表的前面。 Iterator
是一个public
嵌套类NodeList
,因此在声明该类型的变量时,您必须具有质量Iterator
,例如:
int main ()
{
NodeList Nl;
// optionally, insert some items into the list...
NodeList::Iterator p = Nl.begin();
// optionally, increment p if you want to insert in the middle of the list...
N1.insert(p, 5);
return 0;
}
答案 1 :(得分:0)
要插入列表的前面或后面,您必须获取begin
或end
迭代器。
要插入列表中间,您必须获取begin
迭代器,然后递增它,直到达到所需位置(确保没有超过end
迭代器)。
或者,您可以从end
迭代器开始并递减它。
示例:
NodeList list;
list.insertFront(10); // put one element
list.insertFront(20); // put another element
// list is now 20 -> 10
NodeList::iterator it = list.begin();
++it;
list.insert(it, 15); // this inserts 15 before 10
// List now is 20 -> 15 -> 10