2014-09-01 1 views
1

클래스를 사용하기 때문에 지금 C++을 배우려고합니다. 나는 걸릴 것이고 Java에서 오는 것입니다. 저는 현재 "Jumping into C++"라는 책을 읽고 연습을 마칩니다. 연결된 목록에 대한 섹션을 읽은 후에는 내 자신의 링크 된 목록을 만들고 요소를 제거하는 메서드가 있음을 알립니다 (연습의 포인터 사용).C++에서 연결된 목록의 요소 제거

지금까지 연결된 목록에 값을 추가하고 연결된 링크 된 목록을 표시 할 수있었습니다. 요소 제거 메서드를 수행 한 후 내 프로그램에서 특정 메모리 주소의 값을 삭제했다는 것을 명시 적으로 나타내면 목록을 다시 표시하여 내 값이 여전히 삭제 된 메모리 주소에 어떻게 든 나타나는지 찾습니다.

http://pastebin.com/cHZr4cBa

나는 것을 깨닫게 : 여기

// remove an element from the linked list 
void removeElement(int remValue) { 
    // to remove an element, we go through the list, find the value given 
    // if we find it, stop 
    // to remove, disconnect the link 
    // relink the two values now (ie. value 1->2->3->NULL, 2 is removed, 1->3->NULL) 
    LinkedList* current = head; 
    LinkedList* next = current; 
    while(current != NULL) { 
     if(current->value == remValue) { // if match 
      break; // break out of while 
     } 
     else { 
      cout << "Value " << current->value << " does not match " << remValue << ".\n"; 
      next = current; // save in case 
      current = current->pNextValue; // go to next value 
     } 
    } // end while 
    if(current == NULL) { // if we reached end of list 
     cout << "Can't remove value: no match found.\n"; // no match, cant remove 
    } else { // found match 
     cout << "Deleting: " << current << "\n"; 
     delete current; 
     current = next->pNextValue; // current is updated 
    } 
} 

가 (여기서 물건을 것입니다 볼 몇 가지 테스트 포함) 연결리스트에 대한 내 전체 코드입니다 :

내 removeElement 방법입니다 내 코드의 대부분은 효율적이지 않고 실제 링크 된 목록에 대해서는 정상이 아닙니다. 포인터를 찾아 내려고 가장 기본적인 수준의 링크 된 목록에서이를 사용하는 방법에 불과합니다.

+0

:

이 코드를 시도 보다 현대적인 C++ 학습 자료를 찾고 싶습니다 ... – hyde

답변

8

은 제거한 노드의 연결을 해제합니다.

당신은 이전 노드를 추적하고, 현재 노드 next 노드의 next 포인터 지점을 확인해야합니다. 또한 제거 할 노드가 첫 번째 노드 일 때 특수한 경우를 생각해보십시오.

1

삭제 한 노드를 제거하려면 목록의 링크를 업데이트해야합니다.

delete 연산자를 사용하면 메모리의 값이 변경되지 않습니다. 단순히 운영 체제에 메모리에서 해당 위치를 더 이상 사용하지 않고 다른 용도로 다시 사용할 수 있음을 알립니다.

0

@ Joachim Pileborg가 맞습니다. next이 아니라 이전 노드를 기록해야합니다. 당신이 정말로`delete` 필요 (및 C++ (14) 정말`new` 중 하나에서), 당신은 수도 그렇게하지 마십시오 ++ 현대 C에서, 보조 노트로

// remove an element from the linked list 
void removeElement(int remValue) { 
    LinkedList* prev = head; // empty header 
    LinkedList* current = head->pNextValue; // the first valid node 
    while(current != NULL) { 
     if(current->value == remValue) { 
      break; 
     } 
     else { 
      cout << "Value " << current->value << " does not match " << remValue << ".\n"; 
      prev = current; 
      current = current->pNextValue; // go to next value 
     } 
    } 
    if(current == NULL) { // if we reached end of list or the list is empty 
     cout << "Can't remove value: no match found.\n"; 
    } else { 
     cout << "Deleting: " << current << "\n"; 
     prev->pNextValue = current->pNextValue; // unlink the node you remove 
     delete current; // delete the node 
    } 
} 
관련 문제