Niranjan Kotha
Niranjan Kotha

Reputation: 309

Creating a generic linked list in c++ without stl

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;
}

Upvotes: 0

Views: 3007

Answers (1)

Jason C
Jason C

Reputation: 40436

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.

Upvotes: 1

Related Questions