2016-10-03 5 views
0

C++에서 이중 연결 목록을 구현하려고하는데 추가 함수가 제대로 작동하지만 노드 찾기 함수가 목록을 수정하고 있습니다. insertAfter, delete와 같은 다른 모든 함수는이 찾기 함수에 의존하므로 예상대로 작동하지 않습니다.링크 목록 검색 함수 수정 목록

저는 C++을 처음 사용하기 때문에 포인터를 완전히 이해하지 못합니다. C++로 Java 프로그램을 복제하려했습니다. 나는 find 함수에서 헤드 노드에 대한 포인터가 문제를 일으키는 지 확실히 알고 있지만 어떻게 완전히 이해하지는 못합니다. 블록이 두 가지를 비교보다는> 데이터 시작 - D를 할당하는 경우 두 번째에

struct Node{ 
int data; 
Node* next; 
Node* prev; 


Node(int d) { 
    data = d; 
    }; 
}; 


struct DLL { 
    Node* head; 
    Node* tail; 
    int size; 

//Adding a Node to the Doubly LL 
void addNode(Node* n) { 
    //If LL is empty add the first Node 
    if (tail == NULL) { 
     tail = n; 
     head = n; 
    } 
    //Else add add node to the tail. Connect n to the tails next and make n the tail 
    else { 
     tail->next = n; 
     n->prev = tail; 
     tail = n; 
     tail->next = NULL; 
    } 

    size++; 
}; 

//Finding a random Node in the linked List 
//It will return the Node with the FIRST occurrence where data = d 
Node* findNode(int d) { 
//We will start at the head and then traverse through the entire list to find a Node where data = d 
    Node* start = head; 
    if (start == NULL) { 
     cout<<"No element in the List" <<endl; 
     return NULL; 
    } 
    // If head is the Node we are looking for 
    if (start->data = d) { 
     cout<< "Node found with matching data : " << start << endl; 
     return start; 
    } 
    //While next pointer is not null, traverse to search for a match.s 
    while (start->next != NULL) { 
     start = start->next; 
     if (start->data == d) { 
      cout<< "Node found with matching data : " << start << endl; 
      return start; 
     } 
    } 

    cout << "No node found with matching data = " << d <<endl; 
    return NULL; 
}; 
}; 
+0

이러한 문제를 해결하는 올바른 도구는 디버거이다. 스택 오버플로를 묻기 전에 코드를 단계별로 실행해야합니다. 자세한 도움말은 [작은 프로그램 디버깅 방법 (Eric Lippert 작성)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 참조하십시오. 문제를 재현하는 [최소, 완료 및 확인 가능] (http://stackoverflow.com/help/mcve) 예제와 함께 해당 질문을 \ [편집]해야합니다. 디버거. –

+1

이 문제를 찾는 올바른 도구는 컴파일러입니다. ** 경고 **에주의하십시오! – Amit

+1

DLL은 종종 ** d ** ynamic ** ** ** ** ** ** ** ** ** 라이브러리와 연결되기 때문에 DLL에서 이름을 변경하는 것이 좋습니다. –

답변

3
start->data = d 

이 줄 :

다음은 내 코드입니다.

2

이제는 const에 대해 배울 수있는 좋은 시간입니다.

Node* findNode(int d) { 
//We will start at the head and then traverse through the entire list to find a Node where data = d 
    Node* start = head; 
    if (start == NULL) { 
     cout<<"No element in the List" <<endl; 
     return NULL; 
    } 
    // If head is the Node we are looking for 
    if (start->data = d) { 
     cout<< "Node found with matching data : " << start << endl; 
     return start; 
    } 

이 기능은 목록에 쓰기 액세스을 가지고, 당신은 원하지 않는다. 할당 된 값이 null가 아닌 경우

if (start->data = d) { 

이 코드는 dstart->data에 다음 테스트의 값을 할당 : 불행하게도, 당신은 마지막 if 문에서이 액세스를 남용.

//////////////////////vvvvv///////////////// 
Node* findNode(int d) const { 
//We will start at the head and then traverse through the entire list to find a Node where data = d 
    Node* start = head; 
    if (start == NULL) { 
     cout<<"No element in the List" <<endl; 
     return NULL; 
    } 
    // If head is the Node we are looking for 
    if (start->data = d) { 
     cout<< "Node found with matching data : " << start << endl; 
     return start; 
    } 

을 지금의 경우는 컴파일러 오류가 발생합니다 :

우리는 쉽게 const으로이 기능을 표시 할 수 있습니다.

A는 다음과 같은 형태가 될 것이다 코드의 버전을 청소 :

#include <iostream> 

struct Node { 
    int data_; 
    Node* next_ { nullptr }; 
    Node* prev_ { nullptr }; 

    Node(int data) : data_(data) {} 
}; 


struct DLL { 
    Node* head_ { nullptr }; 
    Node* tail_ { nullptr }; 
    int size_ { 0 }; 

    //Adding a Node to the Doubly LL 
    void addNode(Node* node) { 
     //If LL is empty add the first Node 
     if (tail_ == nullptr) { 
      tail_ = node; 
      head_ = node; 
      node->prev_ = node->next_ = nullptr; 
     } 
     //Else add add node to the tail. Connect n to the tails next and make n the tail 
     else { 
      tail_->next_ = node; 
      node->prev_ = tail_; 
      tail_ = node; 
      node->next_ = nullptr; 
     } 

     size_++; 
    } 

    //Finding a random Node in the linked List 
    //It will return the Node with the FIRST occurrence where data = d 
    Node* findNode(int data) const { 
     //We will start at the head and then traverse through the entire list to find a Node where data = d 
     //While next pointer is not null, traverse to search for a match.s 
     for (Node* start = head_; start != nullptr; start = start->next_) { 
      if (start->data_ == data) { 
       std::cout << "Node found with matching data : " << start << '\n'; 
       return start; 
      } 
     } 

     std::cout << "No node found with matching data = " << data << '\n'; 
     return nullptr; 
    } 
}; 

int main() 
{ 
    DLL dll; 

    Node n1(1), n3(3), n5(5); 
    dll.addNode(&n1); 
    dll.addNode(&n3); 
    dll.addNode(&n5); 

    if (dll.findNode(1) != &n1) 
     std::cerr << "wrong result for findNode(1)\n"; 
    if (dll.findNode(2) != nullptr) 
     std::cerr << "wrong result for findNode(2)\n"; 
    if (dll.findNode(3) != &n3) 
     std::cerr << "wrong result for findNode(3)\n"; 
    if (dll.findNode(4) != nullptr) 
     std::cerr << "wrong result for findNode(4)\n"; 
    if (dll.findNode(5) != &n5) 
     std::cerr << "wrong result for findNode(5)\n"; 
} 

라이브 데모 : http://ideone.com/X34EgY