复制列表类的构造函数,而无需在实现中使用任何方法

Copy constructor for List class without using any methods in implementation

本文关键字:实现 方法 任何 列表 构造函数 复制      更新时间:2023-10-16

我正在为列表类编写复制构造函数,要求不使用任何其他方法。

类片段如下:

class List {
     private:
     struct Node {
            NodeData *data;
            Node *next;
           };
           Node *head;
 }; 

要求是为此类编写复制构造函数,并且在实现中不使用任何其他方法,除非我们可以将copy构造函数用于nodedata class

我已经写了复制构造函数,如下所示:

list::list(const list &t){
  Node* q;
  q=new Node;
  while (p!=NULL){
    q->x= p->x;}
}

这不起作用,请帮助如何根据需要编写复制构造函数。

我不同意这是一个奇特的练习的评论者,实际上很有趣,可以尝试做到这一点。以下内容应该让您了解如何尝试:http://ideone.com/ddc7bn

class List {
private:
    struct Node {
        int data; // simplification
        Node *next;
        Node(int d) {
            data = d;
            next = NULL;
        }
    };
protected:
    Node *head;
    Node *tail;
  public:  
    List(int d) : head(new Node(d)), tail(head) {}
    void append(int d) {
        Node* n = new Node(d);
        tail->next = n;
        tail = n;
    }
    List(const List& rhs) {
        if (head) delete head;
        head=new Node(rhs.head->data);
        Node* lhsCurrent = head;
        Node* rhsCurrent = rhs.head->next;
        do {
            lhsCurrent->next = new Node(rhsCurrent->data);  
            rhsCurrent = rhsCurrent->next;
            lhsCurrent = lhsCurrent->next;                  
        } while (rhsCurrent!=NULL);
        tail = lhsCurrent;
    }
 }; 
int main() {
    List first(5);
    first.append(6);
    List second(first);
    return 0;
}