如何将多个相同的节点添加到链表的末尾?

问题描述

我有一个学校项目,我们得到了以下 .h 文件

#ifndef CHAR_H
#define 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:
    //provided
    CharList(); //default constructor
   // ~CharList();  //destructor
    friend std::ostream& operator<<(std::ostream&,const CharList&);
    //void clear();
    //to be implemented
    
    CharList& operator+=(char c);
    
    CharList& insert(unsigned pos,unsigned n,char c);

我在实现插入功能时遇到问题。 Tis 函数接受 3 个参数:链表的位置、我们想要添加节点的位置、节点数量以及我们添加为节点的字符。它是将节点添加到链表的尾端。结果可能如下所示:

testing insert:
pos  n   c   RESULT
===================
0    3   c   c->c->c
1    2   b   c->b->b->c->c

这是我目前所拥有的:

CharList& CharList::insert(unsigned pos,char c) {
    if (pos < 0) {
        pos = 0;
    }
    else if (pos > this->size_) {
        pos = this->size_;
    }

    if (this->tail_ == nullptr) {
       
        while (size_ != n) {
            Node* ptr = new Node{ c,nullptr };
            tail_ = ptr;
            head_ = tail_;
         
            size_++;
            return *this;
       
       }
           
        
    }
    else {

我正在测试当前假设 pos 为 0 且 tail_ 为 null 且字符为 c 的函数。我想重复我的角色 4 次,但我的终端上只显示一次。感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)