0

我写了这个 LinkedList 模板类,它还没有完成——我还没有添加安全特性和更多方法。到目前为止,它可以满足我的需要。但它在某些情况下会失败,我不知道为什么。

template<class data_type> class LinkedList {
private:
    struct Node {
    data_type data;
    Node* prev;
    Node* next;
    Node() : prev(NULL), next(NULL) {}
};
Node* head;
Node* GetLastNode() {
    Node* cur = head;
    while (cur->next != NULL)
        cur = cur->next;
    return cur;
}
public:
LinkedList() {
    head = new Node;
    head->prev = head;
    head->next = NULL;
}
LinkedList(LinkedList<data_type> &to_copy) {
    head = new Node;
    head->prev = head;
    head->next = NULL;
    for (int i = 1; i <= to_copy.NumberOfItems(); i++) {
        this->AddToList(to_copy.GetItem(i));
    }
}
~LinkedList() {
    DeleteAll();
    delete head;
    head = NULL;
}
void AddToList(const data_type data) {
    Node* last = GetLastNode();
    Node* newnode = last->next = new Node;
    newnode->prev = last;
    newnode->data = data;
}
void Delete(const unsigned int position) {
    int currentnumberofitems = NumberOfItems();
    Node* cur = head->next;
    int pos = 1;
    while (pos < position) {
        cur = cur->next;
        pos++;
    }
    cur->prev->next = cur->next;
    if (position != currentnumberofitems)
        cur->next->prev = cur->prev;
    delete cur;
}
void DeleteAll() {
    Node* last = GetLastNode();
    Node* prev = last->prev;

    while (prev != head) {
        delete last;
        last = prev;
        prev = last->prev;
    }
    head->next = NULL;
}
data_type GetItem(unsigned int item_number) {
    Node* cur = head->next;
    for (int i = 1; i < item_number; i++) {
        cur = cur->next;
    }
    return cur->data;
}
data_type* GetItemRef(unsigned int item_number) {
    Node* cur = head->next;
    for (int i = 1; i < item_number; i++) {
        cur = cur->next;
    }
    return &(cur->data);
}
int NumberOfItems() {
    int count(0);
    Node* cur = head;
    while (cur->next != NULL) {
        cur = cur->next;
        count++;
    }

    return count;
}
};

我在问题中陈述了我的问题,这是一个例子:

class theclass {
public:
    LinkedList<int> listinclass;
};

void main() {
    LinkedList<theclass> listoftheclass;
    theclass oneclass;
    oneclass.listinclass.AddToList(5);
    listoftheclass.AddToList(oneclass);
    cout << listoftheclass.GetItem(1).listinclass.GetItem(1);
}

我不知道为什么它运行不正确。

4

2 回答 2

3

您需要实现一个赋值运算符。问题从这里的这个函数开始:

void AddToList(const data_type data) {
    Node* last = GetLastNode();
    Node* newnode = last->next = new Node;
    newnode->prev = last;
    newnode->data = data; <---------------------------- Right there
}

由于 data_type 是您的课程,并且您没有适当的赋值运算符,因此您只是通过成员(浅)复制获得成员。

三法则

您还应该实现一个交换功能,并让您的赋值运算符使用它。

请参阅复制和交换成语

于 2011-07-14T22:33:11.820 回答
2

在 C++03 中,本地类不能是模板参数。移出theclassmain它将起作用。

在 C++0x 中,这个限制被删除了。

于 2011-07-14T22:45:31.300 回答