双向链表分配运算符(withoud使用std :: swap)

时间:2017-03-27 04:38:57

标签: c++ constructor linked-list

所以我必须实现双向链表。我有构造函数,析构函数,许多其他方法,如插入。但是,由于我想申请The Rule of Three,我需要实现复制赋值运算符和复制构造函数。我在互联网上看到了很多解决方案,但所有解决方案都需要std::swapstd::movestd::copy。我无法使用其中任何一种,因为我的所有算法都必须在没有STLboost::的情况下完成。我知道我必须这样开始:

list & list::operator=(const list & that)
{
    if (this != &that)
    {

    }
    return *this;
}

然后我会这样:

if (this != &that)
{
    this->clear();
    node *t = this->head;
    node *o = that.head;
    while (o->next)
    {
        t.append(o.value);
        o = o.next;
        t = t->next
    }
}
return *this;

@Edit:

void menu_list()
{
    char opt;
    int *t;
    list myList = list();
    do {
        display_menu("--- LISTA ---");
        opt = _getche();        
        std::cout << '\n';
        switch (opt) {
        case '1': //reading a list from a text file
        {
            int elements;
            std::ifstream file_stream;// 
            file_stream.open("data.txt"); // 
            if (!file_stream.good()) // 
            {
                std::cout << "Nie udalo sie wczytac pliku!" << '\n';
                break;
            }
            file_stream >> elements; // 
            t = new int[elements]; // stworzenie listy
            for (int i = 0; i<elements; i++)
            {
                file_stream >> *(t + i);    // 
            }
            myList = list(t, elements); //zainicjalizowanie listy
            delete[] t; //
            std::cout << "\nObecny stan listy: "; std::cout << myList.to_string() << '\n';
            break;
        }
        case '2': //deleting an element from a list
        {
            if (myList.is_empty())
            {
                std::cout << "Lista jest pusta! \n"; break;
            }
            int index;
            std::cout << "Podaj indeks elementu do usuniecia: ";
            scanf_s("%d", &index);
            if (myList.size() <= index)
            {
                std::cout << "Lista nie ma tylu elementow!\n"; break;
            }
            else if (index < 0)
            {
                std::cout << "Indeks nie moze byc mniejszy od 0!\n"; break;
            }
            myList.remove(index);
            std::cout << "\nObecny stan listy: "; std::cout << myList.to_string() << '\n';
            break;
        }

list.cpp(列表标题的实现):

#include "list.h"
#include <ctime>


list::list() : head(nullptr), tail(nullptr), n(0)
{
}

list::list(int* t, int n) : head(nullptr), tail(nullptr), n(0)
{
    if (!this->is_empty())
    {
        this->clear();
    }
    for (int i = 0; i < n; i++)
    {
        this->append(t[i]);
    }
}

list::list(const list& obj)
{

}

clear()是一种清除整个列表的方法(headtail = nullptr)和append()是附加值的方法列表的结尾。

现在,我想这是错误的,但我没有任何线索如何使它工作,我想问你们我怎么能这样做

0 个答案:

没有答案