近日在复习数据结构,贴一下练习写的代码,线性链表:
// 如果这段代码对你有用,请任意处置。
#include <iostream>
#include <cstdlib>
using namespace std;
template<class Type> class LinkList;
template<class Type> class SNode
{
friend class LinkList<Type>;
private:
Type data;
SNode<Type> *next;
};
template<class Type> class LinkList
{
public:
LinkList();
~LinkList();
int Length();
void Insert(Type a, Type b);// insert element b after a
bool Delete(Type item);
SNode<Type> *Find(Type item);
bool isEmpty();
void Clear();
Type GetData(const SNode<Type> *p);
SNode<Type> *NextOf(const SNode<Type> *p);
private:
SNode<Type> *head;
};
template<class Type> LinkList<Type>::LinkList()
{
head = NULL;
}
template<class Type> LinkList<Type>::~LinkList()
{
Clear();
}
template<class Type> int LinkList<Type>::Length()
{
int len = 0;
SNode<Type> *p = head;
while(p)
{
len++;
p = p->next;
}
return len;
}
template<class Type> SNode<Type> *LinkList<Type>::Find(Type item)
{
SNode<Type> *p = head;
while(p)
{
if(p->data == item)
{
return p;
}
p = p->next;
}
return NULL;
}
template<class Type> void LinkList<Type>::Insert(Type a, Type b)
{
SNode<Type> *p = NULL;
SNode<Type> *newp = NULL;
if(head == NULL)
{
newp = new SNode<Type>;
newp->data = b;
newp->next = NULL;
head = newp;
}
else if((p = Find(a)) != NULL)
{
newp = new SNode<Type>;
newp->data = b;
p->next = newp;
newp->next = NULL;
}
}
template<class Type> bool LinkList<Type>::Delete(Type item)
{
SNode<Type>* p = head, *q = NULL;
while(p!=NULL)
{
if(p->data == item) break;
q = p;
p = p->next;
}
if(q==NULL)
{
head = p->next;
delete p;
}
else if(p == NULL)
{
return false;
}
else
{
q->next = p->next;
delete p;
}
return true;
}
template<class Type> Type LinkList<Type>::GetData(const SNode<Type> *p)
{
if(p!=NULL)
return p->data;
else
{
cerr<<"Error: ..."<<endl;
exit(1);
}
}
template<class Type> SNode<Type> *LinkList<Type>::NextOf(const SNode<Type> *p)
{
if(p!=NULL)
return p->next;
else
{
cerr<<"Error: ..."<<endl;
exit(1);
}
}
template<class Type> bool LinkList<Type>::isEmpty()
{
return head==NULL;
}
template<class Type> void LinkList<Type>::Clear()
{
SNode<Type> *p = head, *q = NULL;
while(p)
{
q = p;
p = p->next;
delete q;
}
head = NULL;
}
int main()
{
LinkList<int> ll;
SNode<int> *node;
ll.Insert(0,100);
ll.Insert(100,200);
cout<<"Length of ll: "<<ll.Length()<<endl;
node = ll.Find(100);
if(node != NULL)
{
cout<<ll.GetData(ll.NextOf(node))<<endl;
}
ll.Delete(200);
node = ll.Find(200);
if(node != NULL)
{
cout<<ll.GetData(node)<<endl;
}
else
{
cout<<"can't find 200"<<endl;
}
if(!ll.isEmpty())
{
cout<<"not empty"<<endl;
ll.Clear();
}
if(ll.isEmpty()) cout<<"empty now"<<endl;
return 0;
}