Я пытаюсь написать простую программу для печати N-го элемента в связанном списке. Вспомогательные функции были определены в классе Node, но я получаю сообщение об ошибке неопределенной ссылки на вспомогательную функцию, хотя я Включены заголовочные файлы.
Заголовочный файл
#ifndef NODE_H
#define NODE_H
class Node{
public:
int data;
Node* next;
Node* head;
Node();
void push(int);
void insertAfter(Node*,int);
void append(int);
void printList();
int getNth(int);
};
#endif
Вспомогательная функция наряду с функцией getNth, выполняющей нужную задачу.
#include<iostream>
#include "Node.h"
using namespace std;
Node::Node(){
head=NULL;
}
void Node::push(int newData){
Node* newNode=new Node();
Node** head_ref=&head;
if(*head_ref==NULL){
*head_ref=newNode;
return;
}
newNode->data=newData;
newNode->next=(*head_ref);
(*head_ref)=newNode;
}
void Node::insertAfter(Node* prev_node,int newData){
Node* newNode=new Node();
newNode->data=newData;
newNode->next=prev_node->next;
prev_node->next=newNode;
}
void Node::append(int newData){
Node* newNode=new Node();
Node** head_ref=&head;
newNode->data=newData;
newNode->next=NULL;
Node* last=(*head_ref);
if(last==NULL){
*head_ref=newNode;
return;
}
while(last->next!=NULL){
last=last->next;
}
last->next=newNode;
}
void Node::printList(){
Node* n=head;
while(n!=NULL){
cout<<n->data<<" ";
n=n->next;
}
cout<<endl;
}
int Node::getNth(int index){
Node* n=head;
int count=0;
while(n!=NULL){
if(count==index)
return n->data;
count++;
n=n->next;
}
}
Основной файл .
#include<iostream>
#include "Node.h"
using namespace std;
int main(){
Node test;
int n,index;
cin>>n>>index;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
test.push(a[i]);
}
test.printList();
cout<<test.getNth(index);
}
Журнал ошибок
tmp/cc7PXq4M.o: In function `main':
/home/sam/Desktop/C++ Practice/Linked Lists/Singly linked list/getNth.cpp:7: undefined reference to `Node::Node()'
/home/sam/Desktop/C++ Practice/Linked Lists/Singly linked list/getNth.cpp:13: undefined reference to `Node::push(int)'
/home/sam/Desktop/C++ Practice/Linked Lists/Singly linked list/getNth.cpp:15: undefined reference to `Node::printList()'
/home/sam/Desktop/C++ Practice/Linked Lists/Singly linked list/getNth.cpp:16: undefined reference to `Node::getNth(int)'
collect2: error: ld returned 1 exit status
Я знаю, что это простая проблема (связанная с понятиями OOP), но она беспокоит меня, и я не могу продолжить. Любая помощь будет оценена. Спасибо.