线性链表的简单实现

近日在复习数据结构,贴一下练习写的代码,线性链表:


// 如果这段代码对你有用,请任意处置。

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值