2017-12-14 11 views
1

저는 C++을 처음 사용하고 있으며 링크 된 목록을 설정하는 중입니다. 아래 코드가 목록의 머리를 다음으로 업데이트하지 않는 이유는 무엇입니까? 내가링크 된 목록 C++은 헤드의 다음을 업데이트하기 위해 뮤 테이터를 사용할 때 저장하지 않습니다.

void addToList(int dataToAdd){ 
     Node nodeToBeAdded(dataToAdd, NULL); //initilize the node we are going to add with the data that was given by the user 

     if(this->getHead() == NULL){ 
      this->setHead(&nodeToBeAdded); 
      cout << "Added " << this->getHead()->getData() << " to the head of the list\n"; 
      return; 
     } 
     //Calls this even after I set the heads next 
     else if(this->getHead()->getNext() == NULL){ 
      cout<<"Test\n"; 
      this->getHead()->setNext(&nodeToBeAdded); 
     } 
     //IT NEVER REACHES THIS 
     else{ 
      cout<<"super test\n"; 
     } 

    } 

나는 다음과 같은 출력을

Added 3 to the head of the list 
Test 
Test 

덕분에 내가 무엇을 볼 수에서

+1

'nodeToBeAdded' - 해당 변수의 수명은 얼마나됩니까? – PaulMcKenzie

+0

연결 목록을 시도하기 전에 힙에 대한 할당을 가지고 놀아 라. – Beta

+0

요점은 함수가 반환 될 때 연기의 퍼프로 올라갈 변수의 주소를 저장하는 것이 효과가 없다는 것입니다. – PaulMcKenzie

답변

0

을 얻을 다음과 같은 출력을 얻을, 현재 출력이 정확하고 현재의 코드를 기반으로 예상된다. 내가 보는 주된 문제점은 새 노드를 삽입하기위한 포인트를 찾을 때 추가 코드가 목록 맨 앞으로 1-2 단계 만 지나간다는 것입니다. 따라야하는 일반적인 절차는 끝까지 도달 할 때까지 목록을 걸어 내려 가서 새 노드를 추가하는 것입니다. 다음과 같은 것 :

void addToList(int dataToAdd) { 
    Node* curr = this->getHead(); 
    Node nodeToBeAdded(dataToAdd, NULL); 

    // for an empty list assign the head and return 
    if (curr == NULL) { 
     this->setHead(&nodeToBeAdded); 
     cout << "Added " << this->getHead()->getData() << " to the head of the list\n"; 
     return; 
    } 

    // otherwise walk down the list and insert the new node at the end 
    while (curr->getNext() != NULL) { 
     curr = curr->getNext(); 
    } 

    curr->setNext(&nodeToBeAdded); 

    return; 
}