I'm trying to write a simple program to print the Nth element in a linked list.The helper functions have been defined in the Node class but I'm getting an error of an undefined reference of the helper function even though I've included the header files.
Header file
#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
The helper functions along with the getNth function which performs the desired task.
#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;
}
}
The main file.
#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);
}
The error log
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
I know this is a simple issue (related to OOP's concepts) but its disturbing me and I'm not able to proceed.Any help will be appreciated.Thanks.