学习数据结构的笔记(看的是数据结构与算法---c++版)
//singleList.h
#ifndef SINGLELIST_H
#define SINGLELIST_H
template <typename T>
class SLLNode
{
public:
T info;
SLLNode *next;
SLLNode(T el,SLLNode *ptr=0):info(el),next(ptr){}
};
template <typename T>
class SLList
{
SLLNode<T> *head,*tail;
public:
SLList():head(0),tail(0){}
~SLList()
{
for(SLLNode<T> *p;!isEmpty();)
{
p=head->next;
delete head;
head=p;
}
}
bool isEmpty()
{
return head==0;
}
void addToHead(T);
void addToTail(T);
T deleteFromHead();
T deleteFromTail();
void deleteNode(T);
bool isInList(T) const;
void showAll() const
{
SLLNode<T> *p;
for(p=head;p!=0;p=p->next)
cout<<p->info<<" ";
}
};
template <typename T>
void SLList<T>::addToHead(T m)
{
head=new SLLNode<T>(m,head);
if(tail==0)
tail=head;
}
template <typename T>
void SLList<T>::addToTail(T m)
{
if(tail!=0)
{
tail->next=new SLLNode<T>(m);
tail=tail->next;
}
else
head=tail=new SLLNode<T>(m);
}
template <typename T>
T SLList<T>::deleteFromHead()
{
T tmp=head->info;
SLLNode<T> *h=head;
if(head==tail)
head=tail=0;
else
head=head->next;
delete h;
return tmp;
}
template <typename T>
T SLList<T>::deleteFromTail()
{
T tmp=tail->info;
if(head==tail)
{
delete head;
head=tail=0;
}
else
{
SLLNode<T> *h;
for(h=head;h->next!=tail;h=h->next);
delete tail;
tail=h;
tail->next=0;
}
return tmp;
}
template <typename T>
void SLList<T>::deleteNode(T m)
{
if(head!=0)
{
if(head==tail&&head->info==m)
{
delete head;
head=tail=0;
}
else if(head->info==m)
{
SLLNode<T> *tmp=head;
head=head->next;
delete tmp;
}
else
{
SSLNode<T> *pred,*tmp;
for(pred=head,tmp=head->next;tmp!=0&&!(tmp->info==m);pred=pred->next,tmp=tmp->next);
if(tmp!=0)
{
pred->next=tmp->next;
if(tmp==tail)
tail=pred;
delete tmp;
}
}
}
}
template <typename T>
bool SLList<T>::isInList(T m) const
{
SLLNode<T> *tmp;
for(tmp=head;tmp!=0 && !(tmp->info==m);tmp=tmp->next);
return tmp!=0;
}
#endif