2013-05-03 31 views
0

好吧,我想爲鏈接列表創建一個拷貝構造函數。我知道如何爲數組複製構造函數,但不知道鏈接列表。有人可以給我一個想法,我怎麼能做到這一點,謝謝。如何爲鏈接列表創建一個拷貝構造函數

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(常量linked_queue &等) {

ctr = 0; 
front = NULL; 
back = NULL; 

node *p = other.front; 

while (p != NULL) 
{ 
    _push(p->data); 
    p = p->next; 
} 

}

+0

如何查看原始列表中的所有項目並將它們添加到新列表中? – 2013-05-03 04:18:47

+0

我會創建一個新的指針,並將其設置爲等於前,遍歷列表並將原始數據全部複製到前面 – hv16 2013-05-03 04:22:00

+0

我的意思是新列表不是前面的 – hv16 2013-05-03 04:22:51

回答

0

只需遍歷列表,分配一堆具有相同值的節點,並設置next指針。最後,設置frontback指針和ctr,就完成了。

+0

我應該從創建一個新的節點指針開始,並將其設置爲前面並將所有數據從原始指針複製到新指針 – hv16 2013-05-03 04:26:57

+0

您可能最好遵循Vaughn Cato對問題的建議評論部分。這樣你就不太可能偶然地做一些傻事。 – paddy 2013-05-03 04:34:18

+0

是的,你是對的。 – hv16 2013-05-03 04:37:00