0

Can someone help creating generic linkedlist without STL. How do I declare head in main. Is it struct node<>* head ? or struct node* head ? I got a an error using both and it was something like a template declaration cannot appear at block scope

#include <iostream>
using namespace std;


template<class T>
struct node
{
    T data;
    struct node<T>* next;
};

template<class T>
void Push(struct node<T>** H,T dat)
{
    struct node<T> * newnode=(struct node<T> * )malloc(sizeof(struct node<T>)) ;
    newnode->data=dat;
    newnode->next=*H;
    *H=newnode;

}


int main() {

    struct node<>* head=NULL;
    struct node<>* current;
    int a=10;
    float f=10.1;


    Push<int>(&head,a);
    Push<float>(&head,f);


    current=head;
    while(current)
    {
        cout<<current->data;
        current=current->next;
    }

    //code
    return 0;
}
Niranjan Kotha
  • 289
  • 3
  • 14

1 Answers1

1

First of all, this is a weird mix of C and C++ style programming. But let's ignore that and focus on your real question. Your primary issue is that you're not specifying a type parameter when referencing node (should be node<T> when you use it). So changing that first bit to:

template<class T>
struct node
{
    T data;
    struct node<T>* next; 
};

template<class T>
void Push(struct node<T>** H,T dat) // <-- now we use node<T> everywhere
{
    struct node<T> * newnode=(struct node<T> * )malloc(sizeof(struct node<T>)) ;
    newnode->data=dat;
    newnode->next=*H;
    *H=newnode;

}

Should get you where you need to go. There, you're properly referring to it as node<T> everywhere in Push. Same will apply to main(). Now malloc will work, as a node<T> does have a definite size.

That said, you'll find it a bit cleaner to use node<T> *example = new node<T> and delete example instead.

There are a number of other improvements that could be made to move this more into the C++ realm but I'm just focusing on your direct question here; move on to the rest later.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • can you modify the main function too since I am getting some errors like what is the template argument I need to give declaring head. Is it struct node<>* head ? Thanks ! – Niranjan Kotha Aug 24 '16 at 03:59
  • @NiranjanKotha The modifications that need to be made to `main()` and everywhere else are exactly the same as the ones shown here. You might want to check out http://www.tutorialspoint.com/cplusplus/cpp_templates.htm. – Jason C Aug 24 '16 at 05:03