双重链接列表类中的迭代器

问题描述 投票:0回答:2

此代码来自Michael T.Goodrich的“数据结构”一书。我正在自学,所以我没有人为我解释这段代码:

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; 
}
c++ linked-list iterator double
2个回答
1
投票

begin()方法将Iterator返回到列表的前面。 Iteratorpublic嵌套的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; 
}

0
投票

要插入列表的前面或后面,您必须获取beginend迭代器。

要插入列表的中间,你必须获得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
© www.soinside.com 2019 - 2024. All rights reserved.