模板写的单链表(list)

来源:互联网 发布:mac看视频卡死如何退出 编辑:程序博客网 时间:2024/06/07 00:10

模板类的声明和实现不能放到不同的文件中(声明和实现可以分开,但是最好放到一个文件中) 最好都放在.h文件中

下面用模板写的  单链表






//MYLIST_H


#include <iostream>
using namespace std;


template<class T>
struct Node 
{
T m_data;
Node * m_next;
Node(T &n);


};


template <class T>
class CMyList
{
public:
CMyList();
~CMyList();
bool push_front(T &n);
bool remove(T &n);
bool find(T &n);
void print();




private:


Node<T> *m_pHead;
int m_dataCount;



};


template <class T>


void CMyList<T>::print()
{
Node<T>* temp;
temp=m_pHead;
while(temp!=NULL)
{
cout<<temp->m_data<<endl;
temp=temp->m_next;


}
}




template <class T>
Node<T>::Node(T &n)
{
data=n;
next=NULL;


}






template <class T>


CMyList<T>::CMyList()
{
m_pHead=NULL;
m_dataCount=0;


}


template <class T>
CMyList<T>::~CMyList()
{
Node<T> * temp;




while(m_pHead!=NULL)
{
temp=m_pHead->m_next;
free(m_pHead);


m_pHead=temp;
}
/*
for(temp=m_pHead->next,m_pHead!=NULL,m_pHead=temp)
{
free(temp);
}

*/


}
template <class T>
bool CMyList<T>::push_front(T &n)
{
Node<T> * temp=(Node<T>*)malloc(sizeof(Node<T>));
temp->m_data=n;
temp->m_next=m_pHead;
m_pHead=temp;


++m_dataCount;


/*
if(m_pHead!=NULL)
{
temp->next=m_pHead;


m_pHead=temp;

}
else
{
m_pHead=temp;
temp->next=NULL;
}
*/









return true;


}
template <class T>
bool CMyList<T>::remove(T &n)
{


Node<T> * tempNode ,*preTempNode;
tempNode=preTempNode=m_pHead;




while(tempNode!=NULL)
{
if(tempNode->data==n)
{
if(tempNode!=preTempNode)
{
preTempNode->next=tempNode->next;

}
else
{
m_pHead=NULL;


}
free(tempNode);




return true;
}
else
{
preTempNode=tempNode;
tempNode=tempNode->next;


}
}



return false;


}
template <class T>
bool CMyList<T>::find(T &n)
{


Node<T> * temp=m_pHead;
while(temp!=NULL)
{
if(temp->data=n)
{
return true;
}
else
{
temp=temp->next;


}
}
return false;


}
 

原创粉丝点击