Reputation: 33
Line inside main Node<int> *head = takeInput()
is giving error no matching function for call to 'takeInput()'. Can you help me and tell me whats the mistake I am doing here so that I wouldn't do it in future. Thanks!
#include<iostream>
using namespace std;
template<class T>
class Node{
public:
T data;
Node *next;
Node(T x){
data = x;
next = NULL;
}
};
template<typename T>
Node<T> * takeInput(){
T data;
cin>>data;
Node<T> *head = NULL;
Node<T> *tail = NULL;
while(data != -1){
Node<T> *newNode = new Node(data);
if(head == NULL){
head = newNode;
tail = newNode;
}else{
tail->next = newNode;
tail = tail->next;
}
cin>>data;
}
return head;
}
int main(){
Node<int> *head = takeInput();
cout<<head->data;
}
Upvotes: 2
Views: 58
Reputation: 1180
Your code has flaws;
Your compare head == NULL
, it's always be null, every time function runs because, you assigning NULL Node<T> *head = NULL
; at start of function.
And using NULL
not recommended in c++, use nullptr
;
Took liberty and modified your function. there is many ways you can implement below function, for now i took it below way, I am not saying it's the best way.
template<typename T>
void takeInput( Node<T>*& head, T val ){
Node<T>* newNode = new Node<T>( val );
if ( head == nullptr )
{
head = newNode;
}
else
{
Node<T>* tmp = head;
while ( tmp->next != nullptr ) tmp = tmp->next;
tmp->next = newNode;
}
}
int main()
{
Node<int> *head;
takeInput( head, 10 );
takeInput( head, 20 );
takeInput( head, 30 );
std::cout<< head->data << std::endl;
std::cout<< head->next->data << std::endl;
std::cout<< head->next->next->data << std::endl;
}
Upvotes: 1