LinkList设计要点
-类模板,通过头结点访问后继结点
-定义内部结点类型Node,用于描述数据域和指针域
-实现线性表的关键操作(增,删,查,等)
template<typename T>
class LinkList : public List<T>
{
protected:
struct Node :public Object
{
T value;
Node* next;
};
mutable Node m_header;
Node* position(int i) const
{
Node* ret = reinterpret_cast<Node*>(&m_header);
for(int p=0;p<i;p++)
{
ret = ret->next;
}
return ret;
}
int m_length;
public:
LinkList()
{
m_header.next = NULL;
m_length = 0;
}
virtual bool insert(const T& e)
{
return insert(m_length,e);
}
virtual bool insert(int i,const T& e)
{
bool ret = ((0 <= i) && (i <= m_length));
if(ret)
{
Node* node = new Node();
if( node != NULL)
{
Node *current = position(i);
for(int p =0;p<i;p++)
{
current = current->next;
}
node->value = e;
//qDebug() << "i = " << i <<" , e = " << e;
node->next = current->next;
current->next = node;
m_length++;
}
else
{
//抛出异常
qDebug() << "错错了";
}
}
return ret;
}
virtual bool remove(int i)
{
bool ret = ((0 <= i) && (i < m_length));
if(ret)
{
Node* current = position(i);
Node* toDel = current->next;
current->next = toDel->next;
delete toDel;
m_length--;
}
return ret;
}
virtual bool set(int i,const T& e)
{
bool ret = ((0 <=i ) && (i < m_length));
if(ret)
{
Node* current = position(i);
current->next->value = e;
}
return ret;
}
T get(int i) const
{
T ret;
if(get(i,ret))
{
return ret;
}
else
{
//抛出异常
qDebug() << "错了";
}
}
virtual bool get(int i, T& e) const
{
bool ret = ((0 <=i ) && (i < m_length));
if(ret)
{
e = position(i)->next->value;
}
return ret;
}
virtual int length() const
{
return m_length;
}
virtual void clear()
{
while(m_header.next)
{
Node* toDel = m_header.next;
m_header.next = toDel->next;
delete toDel;
}
m_length = 0;
}
~LinkList()
{
clear();
}
};
总结:
-通过类模板实现链表,包含头结点成员和长度成员
-定义结点类型,并通过堆中的结点对象构成链式存储
-为了避免构造错误的隐患,头结点类型需要重定义
-代码优化是编码完成后必不可少的环节