2016-08-24 66 views
0

有人可以幫助創建generic linkedlist而不需要STL。我如何聲明主要頭像。它是struct node <> * head?或者struct node * head?我有一個同時使用一個錯誤,這是像一個模板聲明在塊範圍在C++中創建一個通用鏈接列表,不需要stl

#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; 
} 
+0

爲什麼不使用'new'和'delete'而不是'malloc'和'free'? – Rakete1111

+1

在'Push()'中使用'node '以及'node'。 – songyuanyao

+0

我很熟悉c,因此我習慣了它 –

回答

1

首先,不能出現,這是C和C++編程風格的怪異組合。但讓我們忽略這一點,並專注於您的真正問題。你的主要問題是,當你引用node(當你使用它時應該是node<T>)時你沒有指定一個類型參數。所以改變第一位爲:

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; 

} 

應該讓你去哪裏你需要去。在那裏,你在Push的任何地方都適當地指node<T>。同樣適用於main()。現在malloc將工作,因爲node<T>確實有一定的大小。

也就是說,你會發現使用node<T> *example = new node<T>delete example代替它會更清潔。

還有很多其他的改進可以將這些改進到C++領域,但我只關注你的直接問題;稍後再繼續。

+0

你可以修改主函數,因爲我得到一些錯誤,比如我需要聲明頭的模板參數是什麼。它是struct node <> * head嗎?謝謝 ! –

+0

@NiranjanKotha需要對'main()'和其他地方進行的修改與此處顯示的完全相同。您可能想查看http://www.tutorialspoint.com/cplusplus/cpp_templates.htm。 –