- 目的在于熟悉 C++ 实现链表类、熟悉模板类
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
//前置申明模板类
template <class T>
class List;
//定义节点模板类
template <class T>
class Node
{
//申明友元模板类(必须要前置声明)
friend class List<T>;
public:
Node(T _value)
{
value = _value;
next = NULL;
}
private:
T value;
Node *next;
};
//定义链表模板类
template <class T>
class List
{
public:
List()
{
ptr_head=NULL;
ptr_tail=NULL;
}
void insertnodelist(T _value)
{
int i;
Node<T> * ptr_new = new Node<T>(_value);
if(ptr_head==NULL)
{
ptr_head=ptr_new;
}
else
{
ptr_tail->next = ptr_new;
}
ptr_tail = ptr_new;
}
void printlist()
{
Node<T> * ptr_move = ptr_head;
while(ptr_move!=NULL)
{
cout<<ptr_move->value<<"\t";
ptr_move = ptr_move->next;
}
cout<<endl;
}
private:
Node<T> * ptr_head;
Node<T> * ptr_tail;
};
int main(int argc, char const *argv[])
{
List<int> list;
int i;
for(i=0;i<5;i++)
{
list.insertnodelist(i+1);
}
list.printlist();
return 0;
}