如何为链表创建复制构造函数

How to make a copy constructor for a Linked List

本文关键字:复制 构造函数 创建 链表      更新时间:2023-10-16

我想为链表创建一个复制构造函数。我知道如何复制构造函数的数组,但不为链表。谁能给我一个主意,我怎么能做到这一点,谢谢。

class node 
{

public :
    double data;  
    node *next;  /// pointer that points to next elemnt
    node () { next = NULL; data = 0; }
    node (double val ) { next = NULL; data = val; }
private:

};
队列头

class linked_queue
{

public :
    linked_queue() { front = NULL; back = NULL; ctr = 0;  }   /// default constructor
    bool _empty();  
    void _size();   
    void _front();   
    void _back();   
    void _push(double); 
    void pop();  
    void _display();   
    ~linked_queue(); /// destructor
    linked_queue& operator= ( const linked_queue& rhs );
    linked_queue( const linked_queue& other );
private :
    int  ctr; /// counter
    node  *front;  /// front pointer
    node *back;  ///back pointer
};

编辑:这就是我想出来的

linked_queue::linked_queue(const linked_queue&其他){

ctr = 0;
front = NULL;
back = NULL;
node *p = other.front;
while ( p != NULL )
{
    _push( p->data);
    p = p->next;
}

}

只需遍历列表,分配一堆具有相同值的节点,并设置next指针。最后,设置frontback指针和ctr,完成。