Xcode C ++,无法从main调用指针返回方法

时间:2014-09-15 04:01:29

标签: c++ xcode5

我正在尝试实施LinkedList数据结构。我有main.cppLinkedListClass.cppLinkedListClass.h

这是我的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;
};

我尝试从main调用ktoLast(Node* head, int k)方法,这是我做的:

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;
}

错误讯息: enter image description here

=================== UPDATE =========================

方法实现

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;

}

1 个答案:

答案 0 :(得分:1)

成员函数定义需要写为

Node* LinkedListClass::kToLast(Node* head, int k) { ...

您上面所做的是定义一个具有相同名称的自由函数。此外,如果head始终是当前列表(this)的头部,则不需要将其作为参数传递。