【问题标题】:How do I add an element to the front of a linked list?如何将元素添加到链表的前面?
【发布时间】:2015-11-25 00:21:00
【问题描述】:

这是节点的设置方式:

struct Node {
    Node *next;
    Node *prev;
    T datum;
};

这是我的代码

    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
    void push_front(const T &datum)
    {
        Node newfirst = first; // set newnode to first
        &first = &datum;
        datum = newfirst;

    }



  Node *first;   // points to first Node in list, or 0 if list is empty
  Node *last;    // points to last Node in list, or 0 if list is empty

出于某种原因,我认为这是不对的。

【问题讨论】:

  • 不清楚first和last以及这个方法是类的成员还是独立的数据。

标签: c++ pointers linked-list singly-linked-list


【解决方案1】:

看来你需要以下内容

//this is my code
    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
void push_front(const T &datum)
{
    first = new Node { first, nullptr, datum };

    if ( !last ) last = first;
}

如果您的编译器不支持 new 运算符的初始化列表,那么您可以编写

//this is my code
    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
void push_front(const T &datum)
{
    Node *tmp = new Node();

    tmp->datum = datum;
    tmp->next = first;

    first = tmp;

    if ( !last ) last = first;
}

【讨论】:

    【解决方案2】:

    您希望 (i) 创建一个具有有效内容的新节点,并且 (ii) 设置为列表的第一个节点。你可以像下面的例子那样做:

    void push_front(const T &datum)
    {
        Node* newFirst = new Node;  //construct new Node
        newFirst->next = first;     // set newFirst's next node
        newFirst->datum = datum;   //set the content
        first = newFirst;          //assign new first node;
    }
    

    这只是一个草图;有关更多详细信息,您应该发布更多代码(例如其中一个 cmets 中提到的)。

    要提的另一件事:我更喜欢将 unique_ptr 用于其中一个 Node 指针,例如

    struct Node {
        std::unique_ptr<Node> next;
        Node *prev;
        T datum;
    };
    

    这样你可以很容易地销毁列表(同时避免使用现代 C++ 中经常推荐的new 命令)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2011-06-20
      • 1970-01-01
      相关资源
      最近更新 更多