
code

#ifndef LINKLIST_H#define LINKLIST_H#include "List.h"#include "exception.h"namespace DJLib{template <typename T>class LinkList : public List<T>{protected:struct Node :public object{T value;Node* next;};mutable struct:public object{char reserved[sizeof(T)];Node* next;}m_header;int m_length;Node* position(int i) const{Node* ret = reinterpret_cast<Node*>(&m_header);//需要强制新型类型转换,因为m_header与node不同for(int p = 0; p < i ; p++){ret = ret->next;}return ret;}public:LinkList(){m_header.next = NULL;m_length = 0;}bool insert (const T& e){return insert(m_length,e);}bool insert(int i, const T& e){bool ret = ((0 <= i)&&(i <= m_length));if(ret){Node* node = new Node();if(node != NULL){node->value = e;node->next = position(i)->next;position(i)->next = node;m_length++;}else{THROW_EXCEPTION(noEnoughMemoryException,"No memory to insert element...");}}return ret;}bool remove( int i){bool ret = ((0 <= i)&&(i < m_length));if(ret){Node* toDel = position(i)->next;position(i)->next = toDel->next;delete toDel;m_length--;}return ret ;}bool set(int i, const T& e){bool ret = ((0 <= i)&&(i < m_length));if(ret){position(i)->next->value = e;}return ret ;}T get(int i)const{T ret;if( get(i,ret )){return ret;}else{THROW_EXCEPTION(indexOutOfBoundsException,"Invalid parameter i to get element...");}}bool get(int i, T& e) const{bool ret = ((0 <= i)&&(i < m_length));if(ret){e = position(i)->next->value ;}return ret ;}int find(const T& e) const{int ret = -1;int n = 0;Node* node = m_header.next;while(node){if(node->value == e){ret = n;break;}else{node = node->next;n++;}}return ret;}int length() const{return m_length;}void clear(){while(m_header.next){Node* toDel = m_header.next;m_header.next = toDel->next;}m_length = 0;}~LinkList(){clear();}};}#endif // LINKLIST_H

#include <iostream>#include "LinkList.h"using namespace std;using namespace DJLib;class Test{public:Test(){// throw(0);}};int main(){LinkList<int> list;//s1数组初始长度为5for(int i = 0; i < 5;i++){// list.insert(i);list.insert(0,i);list.set(0,i*i);}for( int i = 0; i < list.length(); i++){cout << list.get(i) << endl;}list.remove(3);for( int i = 0; i < list.length(); i++){cout << list.get(i) << endl;}// LinkList<Test> lst1;// // Test t;cout <<"D.J.Software" << endl;return 0;}
增加find函数后的main.c
#include <iostream>
#include "LinkList.h"
#include "SeqList.h"
using namespace std;
using namespace DJLib;
class Test : object
{
int i;
public:
Test(int v = 0)
{
i = v;
}
bool operator == (const Test& t)
{
return (i == t.i);
}
};
int main()
{
Test t1(1);
Test t2(2);
Test t3(3);
LinkList<Test> list;
list.insert(t1);
list.insert(t2);
list.insert(t3);
cout << list.find(t2) << endl;
return 0;
}
