C++에서 연결된 목록 클래스를 구현하려고하는데 문제가 있습니다. 새로운 노드를 추가하는 + = 연산자가 있습니다.C++은 다른 방법으로 변경 내용을 저장하지 않습니다.
연결리스트 클래스 인터페이스 :
template <typename Type>
class LinkedList {
public:
LinkedList<Type>* head;
// linked list stracture
Type data;
LinkedList<Type>* next;
// others ....
size_t length;
public:
LinkedList();
~LinkedList();
void initializeHead(LinkedList<Type>* headPtr);
size_t size() const;
LinkedList& operator+=(const Type& add);
void operator-=(const Type& remove);
LinkedList<Type>& operator[] (const size_t index) const;
bool operator== (const LinkedList<Type> &versus) const;
friend ostream& operator<< (ostream& out,LinkedList& obj);
};
여기에 내가 가지고있는 + = 과부하 구현 :
template <typename Type> LinkedList<Type>& LinkedList<Type>::operator [](const size_t index) const {
if(index < 0 || index >= length) // invaild argument
throw exception();
// continue
LinkedList<Type>* p = head;
for(size_t i = 0; i < index; ++i) p = p->next; // we are at what we want
return *p;
}
: 또한
template <typename Type> LinkedList<Type>& LinkedList<Type>::operator +=(const Type& add) {
// head ptr - :)
LinkedList<Type>* p = head->next;
// go to the end
while(p) p = p->next;
// now on end - create new..!!!
try {
p = new LinkedList<Type>;
} catch (bad_alloc& e) {
cout << "There\'s an allocation error....";
} catch (...) {
cout << "An unknown error.." << endl;
}// fill and done
p->data = add;
p->next = NULL;
// increment length .........
++head->length;
// done ............
return *p;
}
, 나는 "배열"액세스 과부하 방법을
제대로 작동합니다. - 디부 거를 확인했는데
문제는 + + = "head-> next"에 새 노드를 저장하지 않습니다. 이유는 무엇입니까? finish + = method 다음에 head-> next가 null과 같습니다.
새로운 할당이 head-> next에 연결되지 않는 이유를 아는 사람이 있습니까?
감사합니다.
스택으로 구현하려고하면 훨씬 간단 해집니다. –
링크 된 목록은 벡터보다 좋지 않습니다. 실제로는 속도가 느리고 임의 액세스를 지원하지 않습니다. 적어도 O (n)이 아닌 일정한 시간 삽입을 갖는 이러한 LL을 구현하십시오. –