2017-03-31 1 views
-1

단일 순환 링크 목록에서 모든 노드를 제거하려고합니다. 하지만 다음있어 오류 :C++ 순환 링크 목록 - 모든 노드 제거

void StudentLinkList::removeAll() { 
    StudentData *traversePointer = this->head; 

    while (this->head != nullptr) { 
     this->head = this->head->getNext(); 
     delete traversePointer; 
     traversePointer = nullptr; 
     traversePointer = this->head; 
     this->size--; 
    } 
} 

내가이 줄에 오류 :

malloc: *** error for object 0x1005068f0: pointer being freed was not allocated 

다음은 함수

delete traversePointer; 

내 질문은 그 traversePointer 루프 동안의 할당되지 않은 이유 오류에 표시된대로?

+0

, 그러나 당신의 질문은 무엇입니까? – user463035818

+0

순환 링크리스트에서, 'this-> head = this-> head-> getNext();'는 처음으로 돌아 왔을 때 어떻게 동작할까요? 디버거를 사용하십시오 .... –

+2

오류는 매우 솔직하게 설명력이 있습니다 ... 당신은 정말 기뻐해야합니다 ... 나는 이런 종류의 오류를 받았으면 좋겠어 ... – WhiZTiM

답변

0

그동안 같아야 루프가 완료되면, 다음 this-> = nullptr 헤드 세트

while(this->size){ 

. 루프에서 traversePoitner = nullptr을 설정할 필요가 없습니다.

대체 버전 (내가 아직 확인하지 않은 경우), 그 크기는 목록이 원형 만하는 것이 올바른 것> this-에 의존하지 않습니다

void StudentLinkList::removeAll() { 
    if(this->head == nullptr) 
     return; 
    StudentData *traversePointer = this->head; 
    StudentData *deletePointer; 
    do{ 
     deletePointer = traversePointer; 
     traversePointer = traversePointer->getNext(); 
     delete deletePointer; 
    }while(traversePointer != this->head); 
    this->head = nullptr; 
    this->size = 0; 
} 
당신은 아마 오류를 수정하려는
+0

이미 삭제할 때 this-> head = nullptr을 설정하고 traversePoitner를 null로 설정해야하는 이유는 무엇입니까? 끝에서 트래버스 포인터는 머리와 같습니다. 따라서 traverse 포인터를 null로 설정하면 헤드 포인터가 자동으로 null로 설정됩니다. –

+0

@IdreesAshraf - this-> head는 노드에 대한 포인터입니다. traversePointer는 this-> head에 대한 참조가 아닌 this-> head의 복사본과 node에 대한 별도의 포인터입니다. 또한 루프가 완료되면 this-> head는 원형 목록이기 때문에 원래 값으로 돌아갑니다. – rcgldr

+0

나는 그것을 얻었다. 조금 혼란 스러울 때, 트래버스 포어와 헤드 포인터가 같은 물체를 가리키고 있습니다. 그래서 traversePointer를 삭제하면 두 포인터가 가리키는 동일한 객체가 삭제되지 않습니까? –