2014-09-15 3 views
0

LinkedList 데이터 구조를 구현하려고합니다.Xcode C++에서 포인터 반환 메서드를 호출 할 수 없습니다.

int main(int argc, const char * argv[]) 
{ 
    LinkedListClass* myList = new LinkedListClass(); 

    myList->insert(3); 
    myList->insert(4); 
    myList->insert(2); 
    myList->insert(7); 
    myList->display(); 

    Node* head = myList->head; 
    int k = 3; 

    int val = myList->ktoLast(head, k)->data; 
    cout << val << endl; 


    return 0; 
} 

오류 메시지 : 그래서 main.cpp, LinkedListClass.cppLinkedListClass.h

이 여기에 내가 주에서 ktoLast(Node* head, int k) 메소드를 호출하려고 내 LinkedListClass.h

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

class LinkedListClass 
{ 
public: 
    Node* head; 
    LinkedListClass(); 
    ~LinkedListClass(); 

    void insert(int value); 
    void display(); 
    Node* ktoLast(Node* head, int k);//<-- this compile fine if I didn't call it from main 

private: 
    Node* tail; 
}; 

이다, 여기에 내가 해냈어 방법은 다음과 같습니다 enter image description here

==================== 업데이트 ==== =====================

Node* ktoLast(Node* head, int k) 
{ 
    Node* current = head; 
    int length = 0; 

    // find the length of the list 
    while (current) 
    { 
     length++; 
     current = current->next; 
    } 
    current = head; // reset back to head 
    if (k > length || k < 1) return NULL; 

    int count = 0; 
    while (length - count != k) 
    { 
     count++; 
     current = current->next; 
    } 

    return current; 

} 
+0

함수 정의는 어디에 있습니까? 아마도 LinkedListClass.cpp에 있습니다. 컴파일되고 링크되어 있습니까? – sfjac

+0

@sfjac 위 메소드 구현을 추가했습니다. 네, main에서 메서드를 호출하지 않으면 프로그램이 잘 컴파일됩니다. 'ktoLast (Node * head, int k)'를 – Heisenberg

답변

1

멤버 함수 정의

Node* LinkedListClass::kToLast(Node* head, int k) { ... 
로 기록 될 필요가있어서 구현

위의 내용은 같은 이름의 자유 함수를 정의하는 것입니다. 또한 head이 항상 현재 목록 (this)의 헤드 인 경우 '인수로 전달할 필요가 없습니다.

+0

에서 호출했을 때 오류가 발생했습니다. 나는 그것을 간과했다. – Heisenberg