【问题标题】:how to use += operator to add characters to a linked list?如何使用 += 运算符将字符添加到链表?
【发布时间】:2021-07-02 17:03:50
【问题描述】:

我有这个 Char.h 文件:

struct Node {
    char value;
    Node* next;
};

class CharList {
private:
    Node* head_;  //point to the first Node of the list
    Node* tail_;  //point to the last Node of the list
    unsigned size_; //the number of Nodes in the list
public:
    CharList();
    friend std::ostream& operator<<(std::ostream&, const CharList&);
    CharList& operator+=(char c);
};

而且我需要实现+= 运算符,但我真的很挣扎,我不知道该怎么做。

这是我目前所拥有的:

CharList& CharList::operator+=(char c) {
    
    Node* ptr = new Node;
    ptr->value = c;
    ptr->next = nullptr;
    this->head_ +=c;

    return *this;
}

在main() 函数上,我希望它能够运行,以便结果看起来像这样:

+='M' M
+='C' M->C
+='S' M->C->S

【问题讨论】:

  • this-&gt;head_ +=c; 为什么要向指针添加char?

标签: c++ linked-list nodes


【解决方案1】:

您很接近,您只是没有将新创建的Node 正确链接到列表的其余部分。试试这个:

CharList& CharList::operator+=(char c) {
    
    Node* ptr = new Node;
    ptr->value = c;
    ptr->next = nullptr;

    if (!head_) head_ = ptr;
    if (tail_) tail_->next = ptr;
    tail_ = ptr;
    ++size_;

    return *this;
}

Demo

不要忘记根据Rule of 3/5/0 向CharList 添加析构函数、复制/移动构造函数和复制/移动赋值运算符。

【讨论】:

  • @TedLyngmo 可以,是的。我只是更喜欢更明确地说明它
猜你喜欢
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2011-06-16
相关资源
最近更新 更多