2012-06-05 4 views
0

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에 연결되지 않는 이유를 아는 사람이 있습니까?

감사합니다.

+0

스택으로 구현하려고하면 훨씬 간단 해집니다. –

+0

링크 된 목록은 벡터보다 좋지 않습니다. 실제로는 속도가 느리고 임의 액세스를 지원하지 않습니다. 적어도 O (n)이 아닌 일정한 시간 삽입을 갖는 이러한 LL을 구현하십시오. –

답변

2

while(p) p = p->next; p가 NULL

이며 p = new LinkedList<Type>;을하지만, 옆 머리에 쪽을 연결하지 않습니다 후. 대신

+0

고마워, 그게 더 좋다, 새로운 노드를 구할 수있어 .- 목록 끝 부분에 NULL이 없다는 것 같아. 왜 그런지 알아? – nimrod

+0

p-> data = data; p-> 다음 = NULL; 목록의 마지막 노드가이 새 노드를 가리켜 예상 결과 (NULL이 끝에 있음)를 가져와야한다고 생각합니다. – Rahul

0

:

// go to the end 
while(p) p = p->next; 

당신이 필요합니다

head->next = p; 
0

다른 답변이 말하는 것처럼, 추가하려고 할 때 목록을 넘어.

template <typename Type> LinkedList<Type>& LinkedList<Type>::operator +=(const Type& add) 
{ 
    LinkedList<Type> *last; 

    // Find the last node in the list 
    for (last = head; last != 0 && last->next != 0; last = last->next) 
    { 
    } 

    // `last` now points to the last node in the list, or is zero 
    // If zero (i.e. NULL) then list is empty 

    if (last == 0) 
    { 
     head = new LinkedList<Type>; 
     head->next = 0; 
     head->data = add; 
     head->length = 0; 
    } 
    else 
    { 
     last->next = new LinkedList<Type>; 
     last->next->next = 0; 
     last->next->data = add; 
    } 

    // We can safely use `head` as we are sure it won't be zero 
    head->length++; 

    // Return the added node 
    return (last != 0 ? *last->next : *head); 
} 
+0

음 ... 좋아, 내가 직접'delete' 문제를 고치려고합니다. 정말 고마워요! – nimrod

+0

@nimrod 생성자가'head' 멤버 변수를 초기화하는지 확인하십시오. 가급적 다른 변수들도 있습니다. 그러면 내가 게시 한 함수에서 이들을 제로화 할 필요가 없습니다. –

0

임시 변수를 사용하여 마지막 노드를 저장 한 다음 마지막 노드가 새 노드를 가리킬 수도 있습니다.

이것은 샘플 코드입니다. 첫 노드 등을 추가하는 것과 같은 몇 가지 상황을 처리해야합니다.

LinkedList<Type>* temp = NULL; 
while(p) 
{ 
    temp = p; 
    p = p->next; 
} 

try 
{    
    p = new LinkedList<Type>;   
    temp->next = p; 
} 
관련 문제