实现链表的复制构造函数

时间:2013-10-18 00:04:53

标签: c++ linked-list copy-constructor

我正在尝试使用c ++实现链表的复制构造函数。是否可以先将链表的元素复制到数组中,然后制作array[i] = list? (list被视为参数。)

template <typename Type>
Single_list<Type>::Single_list( Single_list<Type> const &list ):
list_head( 0 ),
list_tail( 0 ),
node_count( 0 ) {

    // enter your implementation here
    for(int i = 0; i < node_count; i++){
    *tmp_array = new array[node_count];
    tmp_array[i] = list;


}

提前抱歉,我不熟悉编码..

好的,这是:

template <typename Type>
class Single_list {
    private:
        Single_node<Type> *list_head;
        Single_node<Type> *list_tail;
        int node_count;


    public:
        Single_list();
        Single_list( Single_list const & );
        ~Single_list();

        // Accessors

        int size() const;
        bool empty() const;

        Type front() const;
        Type back() const;

        Single_node<Type> *head() const;
        Single_node<Type> *tail() const;

        int count( Type const & ) const;

        // Mutators

        void swap( Single_list & );
        Single_list &operator = ( Single_list const & );

        void push_front( Type const & );
        void push_back( Type const & );

        Type pop_front();

        int erase( Type const & );

    // Friends

    template <typename T>
    friend std::ostream &operator << (std::ostream &, Single_list<T> const&);
};

template <typename Type>
Single_list<Type>::Single_list():
list_head( 0 ),
list_tail( 0 ),
node_count( 0 ) {
    // empty constructor
}

template <typename Type>
Single_list<Type>::Single_list( Single_list<Type> const &list ):
list_head( 0 ),
list_tail( 0 ),
node_count( 0 ) {

    Single_List<Type> *tmp_ptr = 0;

    for(tmp_ptr = head(); tmp_ptr !== 0; tmp_ptr->next()){
         //my copy constructor so far..
        tmp_ptr->retrieve() = list;
    }
}

template <typename Type>
Single_list<Type>::~Single_list() {

    Single_list<Type> *tmp_ptr = 0; //temp pointer initialized

    for(tmp_ptr = head(); tmp_ptr !==0; tmp_ptr-next()){
        //iterate through single_list, then delete
        delete tmp_ptr;
    }
}

哦和操作员:

template <typename Type>
Single_list<Type> &Single_list<Type>::operator = (Single_list<Type> const &rhs) {
    Single_list<Type> copy( rhs );

    swap( copy );

    return *this;

1 个答案:

答案 0 :(得分:0)

如果你这样做是为了开发你的编码技巧,那么你可能想学习实现std::list<>的代码。否则,您可以使用它。

移动构造函数和移动赋值运算符=已在标准模板库(STL)中的C ++ 0x和C ++ 11中实现。只需包含适当的标题(#include <list>)并使用它即可使用它们(使用兼容的编译器)。

以下是一个简单的示例:

#include <list>

using namespace std;

int main()
{
    list<int> my_list;
    for (int i = 0; i < 1000000; ++i) // make a big list
        my_list.push_back(i);

    list<int> my_copied_list = my_list;       // copy the list using the conventional assignment operator (slow)
    list<int> my_moved_list  = move(my_list); // move the list using the move assignment operator (fast)
}
相关问题