我正在用 C++ 实现一个简单的链表。 我有一个错误,但我没有看到它:(
#include <stdexcept>
#include <iostream>
struct Node {
Node(Node *next, int value):
next(next), value(value) {
}
Node *next;
int value;
};
class List {
Node *first;
int len;
Node *nthNode(int index);
public:
List():first(0),len(0){
}
// Copy - Konstruktor
List(const List & other){
};
// Zuweisungs - Operator O(len +other.len)
List &operator=(const List &other) {
clear();
if(!other.len) return *this;
Node *it = first = new Node(0,other.first->value);
for (Node *n = other.first->next; n; n = n->next) {
it = it->next = new Node(0, n->value);
}
len = other.len;
return *this;
}
// Destruktor
~List(){
};
void push_back(int value){
};
void push_front(int value){
Node* front = new Node(0,value);
if(first){
first = front;
front->next = 0;
}else{
front->next = first;
first = front;
}
len++;
};
int &at(int index){
int count = 0 ;
int ret ;
Node *it = first;
for (Node *n = first->next; n; n = n->next) {
if(count==index) ret = n->value;
count++;
}
return ret ;
};
void clear(){
};
void show() {
std::cout << " List [" << len << " ]:{ ";
for (int i = 0; i < len; ++i) {
std::cout << at(i) << (i == len - 1 ? '}' : ',');
}
std::cout << std::endl;
}
};
/*
*
*/
int main() {
List l;
// l. push_back(1);
// l. push_back(2);
l. push_front(7);
l. push_front(8);
l. push_front(9);
l.show();
// List(l). show();
}
它有效……但输出是:
List [3 ]:{ 0,134520896,9484585}
最佳答案
push_front
逻辑错误。它应该看起来像这样:
void push_front(int value){
first = new Node(first, value);
++len;
}
虽然我们正在处理它,但您的 operator=
不是异常安全的。在复制构造函数中实现复制并使用 copy-and-swap 习惯用法进行分配:
List& operator=(List other) { swap(other); return *this; }
void swap(List& other) {
Node* tnode = first; first = other.first; other.first = tnode;
int tlen = len; len = other.len; other.len = tlen;
}
另一方面,不要实现at
成员函数;随机访问效率很低,不应该被鼓励。而是实现迭代器。
关于c++ - 错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2964685/