Creating a generic linked list in c++ without stl -
can creating generic linkedlist
without stl
. how declare head in main. struct node<>* head ? or struct node* head ? got error using both , template declaration cannot appear @ 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; }
first of all, weird mix of c , c++ style programming. let's ignore , focus on real question. primary issue you're not specifying type parameter when referencing node
(should node<t>
when use it). changing 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) // <-- 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 need go. there, you're referring node<t>
everywhere in push
. same apply main()
. malloc
work, node<t>
have definite size.
that said, you'll find bit cleaner use node<t> *example = new node<t>
, delete example
instead.
there number of other improvements made move more c++ realm i'm focusing on direct question here; move on rest later.
Comments
Post a Comment