I'm trying to implement a LinkedList
data structure. So I have main.cpp
, LinkedListClass.cpp
, and LinkedListClass.h
Here's my 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;
};
I tried to call the ktoLast(Node* head, int k)
method from main, here's how I did it:
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;
}
The error message:
===================UPDATE=========================
The method implementation
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;
}
The member function definition needs to be written as
Node* LinkedListClass::kToLast(Node* head, int k) { ...
What you have above is defining a free function with the same name. Also, if head
is always the head of the current list (this
)' it doesn't need to be passed as an argument.