#include<iostream>
using namespace std;
template<class E,class K>
class SortedChainNode{
public:
E data;
SortedChainNode<E,K> *link;
};
template<class E,class K>
class SortedChain{
public:
SortedChain(){first = 0;}
~SortedChain();
bool IsEmpty()const{return first==0;}
int Length()const;
bool Search(const K&k,E&e);
SortedChain<E,K>& Delete(const K&k,E&e);
//SortedChain<E,K>& Insert(const E &e);
SortedChain<E,K>& DistinctInsert(const E &e);
void Output(ostream& out)const;
private:
SortedChainNode<E,K> *first;
};
class BadInput{
public:
BadInput(){
cout<<"Bad Input!"<<endl;
}
};
template<class E,class K>
SortedChain<E,K>::~SortedChain(){
SortedChainNode<E,K>*next;
//指向下一个节点
while(first){
next=first->link;
delete first;
first = next;
}
}
//重载操作符
template<class E,class K>
ostream& operator<<(ostream& out,const SortedChain<E,K>&x){
x.Output(out);
return out;
}
//输出链表
template<class E,class K>
void SortedChain<E,K>::Output(ostream& out)const{
SortedChainNode<E,K>*current;
for(current=first;current;current=current->link){
out<<current->data;
if(!current->link){
out<<""<<endl;
}else{
out<<",";
}
}
}
//输入与k匹配的元素
//结果放到e里面
//如果没有则返回false
template<class E,class K>
bool SortedChain<E,K>::Search(const K&k,E&e){
SortedChainNode<E,K> *p = first;
//搜索与k相匹配的元素
for(;p&&p->data<k;p=p->link);//需要重载<操作符
//验证是否与k匹配
if(p&&p->data==k){
e=p->data;
return true;
}
return false;
}
//删除与k相匹配的元素
//并将删除的元素放到e
//如果不存在匹配则返回异常BadInput
template<class E,class K>
SortedChain<E,K>& SortedChain<E,K>::Delete(const K&k,E&e){
SortedChainNode<E,K> *p = first;
SortedChainNode<E,K> *tp = 0;
//搜索与k相匹配的元素
for(;p&&p->data<k;tp=p;p=p->link);//需要重载<操作符
//验证是否与k匹配
if(p&&p->data==k){
e=p->data;
if (tp){
tp->link=p->link;
}else{
first=p->link;
}
delete p;
return *this;
}
throw(BadInput());//不存在相匹配的元素
}
//如果表中不存在关键值与e相同的元素则插入
//否则引发异常BadInput
template<class E,class K>
SortedChain<E,K>& SortedChain<E,K>::DistinctInsert(const E&e){
SortedChainNode<E,K>*p=first;
SortedChainNode<E,K>*tp=0;
//搜索与k相匹配的元素
for(;p&&p->data<e;tp=p,p=p->link);//需要重载<操作符
//验证是否与k匹配
if(p&&p->data==e)
throw(BadInput());//不存在相匹配的元素
//若没有出现重复关键值,则产生一个关键值为e的节点
SortedChainNode<E,K>*q = new SortedChainNode<E,K>;
q->data=e;
//将节点加到tp之后
q->link=p;
if(tp)
tp->link=q;
else
first=q;
return *this;
}
int main(){
SortedChain<int,float>mySortedChain;
mySortedChain.DistinctInsert(12);
mySortedChain.DistinctInsert(1314);
mySortedChain.DistinctInsert(520.1314);
mySortedChain.DistinctInsert(1223);
mySortedChain.DistinctInsert(1030);
mySortedChain.DistinctInsert(8);
mySortedChain.DistinctInsert(40);
cout<<mySortedChain<<endl;
return 0;
}