*C++单向链表模板函数的实现
单向链模板函数的头文件和实现函数
链表的功能:
1.实现从头/从尾插入数据;
2.实现从头/从尾删除数据;
3.实现寻找某个点的数据;
4.实现在某个节点插入数据;
5.实现删除摸个数据的节点;
6.实现判断某个值是否在链表中;
技术水平有限,如果代码某个地方有差错,随时留言交流,3Q
#ifndef LIST_H_
#define LIST_H_
template<class T>class Listnode
{
public:
T data;
Listnode *next;
Listnode(){next = 0;}
Listnode(T value,Listnode *p=0)
{
data = value;
p = next;
}
};
template<class T>class Listt
{
private:
Listnode<T> *head,*tail;
Listnode<T> *setpot(int p);
public:
Listt(){head = tail = 0;}
~Listt();
int isempty(){return head = 0 ;}
void addFromHead(T);
void addFromTail(T);
T deleteFromHead();
T deleteFromTail();
bool inset(const int p,const T value);
void deleteListnode(T);
bool isinList(T)const;
};
#endif // LIST_H_
#include "List.h"
#include <iostream>
using namespace std;
template<class T>
Listt<T>::~Listt()
{
for(Listnode<T> *p;!isempty();)
{
p = head->next;
delete head;
head = p;
}
}
template<class T>
void Listt<T>::addFromHead(T adh)
{
head = new Listnode<T> ( adh,head);
if(tail == 0)
tail == head;
}
template<class T>
void Listt<T>::addFromTail(T adt)
{
if(tail != 0)
{
tail->next = new Listnode<T> (adt);
tail = tail->next;
}
else
head = tail = new Listnode<T> (adt);
}
template<class T>
T Listt<T>::deleteFromHead()
{
T el = head->data;
Listnode <T> *temp = head;
if(head == tail)
head = tail =0;
else
head = head->next;
delete temp;
return el;
}
template<class T>
T Listt<T>::deleteFromTail()
{
T el = tail->data;
if(head == tail)
head = tail =0;
else
{
Listnode <T> *temp ;
for(temp = head;temp != tail;temp = temp->next);
delete tail;
tail = temp;
tail->next = 0;
}
return el;
}
template<class T>
void Listt<T>::deleteListnode(T delN)
{
if(head != 0)
{
if(head == tail && head->data == delN)
{
delete head;
head =tail =0;
}
else if(delN == head->data)
{
Listnode<T> *temp = head;
head = head->next;
delete temp;
}
else
{
Listnode<T> *pred,*temp;
for(pred=head,temp=head->next;temp != 0 && !(temp->data != delN);pred = pred->next,temp = temp->next);
if(temp != 0)
{
pred->next = temp->next;
if(temp = tail)
tail = pred;
delete temp;
}
}
}
}
template<class T>
Listnode<T>* Listt<T>::setpot(int i)
{
int num=0;
if(i==-1)
return head;
Listnode<T> *p=head->next;
while(p!=NULL&&num<i)
{
num++;
p=p->next;
}
return p;
}
template<class T>
bool Listt<T>::inset(const int i,const T value)
{
Listnode<T> *p,*q;
if(p=setpot(i)==NULL)
{
cout<<"error insert!\n";
return false;
}
q = new Listnode<T>(value,p->next);
p->next = q;
if(p= tail)
tail = p;
return true;
}
template<class T>
bool Listt<T>::isinList(T el)const
{
Listnode<T> *temp;
for(temp = head;temp != 0&&!(temp->data == el);temp == temp->next);
return temp != 0;
}