나는 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();
}
를 :(볼 수 없습니다 ...하지만 출력은 다음과 같습니다
목록 [3] : {0,134520896,9484585}
내가 왜 undestand 연산자 = 왜 스왑을 사용해야합니다. 내가 2 목록을 가지고 다른 하나를 할당한다면, 나는 그 fisrt가 목록의 하나의 메모리 공간을 가리키는 게으른 자원 절약 머리를 가진 사본이 될 것이기를 바란다. –
@denard bardadym,'new Node' 호출 중 하나가 실패하면 어떤 상태가 될까요? 복사 및 스왑 이디엄은 복사본이 이미 성공할 때까지 할당 대상을 변경하지 않습니다. 스왑 자체는 절대로 버리지 않습니다. –
push_front()는 marcelo와 같아야합니다. at() 함수에서 잘못된 Node *로 시작합니다. 목록에서 first -> next로 시작하면 "first"여야합니다. – akira