我正在尝试使用 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;