程序代码:
//单链表的c++模板
#include <iostream.h>
template <class T>
class Node
{
public:
T data;
Node<T> * next;
};
template <class T>
class LinkList
{
public:
LinkList( ) ; //无参构造函数
LinkList(T a[ ], int n); //有参构造函数
~LinkList( ){} //析构函数
int Length( ); //求表长
T Get(int const i); //返回指定位置元素
Node<T>* Locate(T const x ); //返回指定元素地址
void Insert(int i, T x){} //指定位置插入元素
T Delete(int i){} //删除指定位置元素
private:
Node <T> *first;
};
template <class T>
Node<T> * LinkList<T>::Locate( T const x )
{
Node<T> * temp = first;
while( x != temp->data )
{
temp = temp->next;
}
return temp;
}
template <class T>
T LinkList<T>::Get(int const i)
{
int count = 1;
Node<T> *temp = first;
while( i != count )
{
temp = temp->next;
++count;
}
return temp->data;
}
template <class T>
int LinkList<T> ::Length()
{
int count = 0;
Node<T> *temp = first;
while( 0xcccccccc != (const unsigned int) temp )
{
temp = temp->next;
++count;
}
return count;
}
template <class T>
LinkList<T> :: LinkList()
{
first = NULL;
}
template <class T>
LinkList<T> :: LinkList( T a[], int n)
{
LinkList();
Node<T> *temp = NULL;
while( 0 != n )
{
temp = new Node<T>;
temp->data = a[n-1];
temp->next = first;
first = temp;
--n;
}
}
int main()
{
int a[] = {1, 2, 3, 5, 7, 11, 13};
LinkList<int> instance( a, 7 );
cout << instance.Get( 5 ) << endl;
cout << instance.Locate( 5 ) << endl;
cout << "The length is :" << instance.Length() << endl;
return 0;
}