1. 设计思路(游标)
提供一组遍历相关的函数,以线性的时间复杂度遍历链表
函数 | 功能说明 |
---|---|
move() | 将游标定位到目标位置 |
next() | 移动游标 |
current() | 获取游标所指向的数据元素 |
end() | 游标是否到达尾部 |
2. 遍历函数原型设计
bool move(int i,int step = 1);
bool end();
T current();
bool next();
3. 实现
int move(int i,int step = 1)
{
bool ret = (0<=i) && (i<m_length) && (step>0);
if(ret)
{
m_current = position(i)->next;
m_step = step;
}
return ret;
}
bool end()
{
return (m_current == NULL);
}
T current()
{
if( !end() )
{
return m_current->value;
}
else
{
THROW_EXCEPTION(IndexOutOfBoundsException,"No value at current position...");
}
}
bool next()
{
int i = 0;
while((i<m_step) && !end())
{
m_current = m_current->next;
i++;
}
return (i == m_step);
}
int main()
{
LinkList<int> list;
for(int i=0;i<5;i++)
{
list.insert(0,i);
}
for(list.move(0);!list.end();list.next())
{
cout << list.current() << endl;
}
return 0;
}
输出:4 3 2 1 0
优化
封装结点的申请和删除操作
virtual Node* create()
{
return new Node();
}
virtual void destory(Node* pn)
{
delete pn;
}
4. 小结
单链表的遍历需要在线性时间内完成
在单链表内部定义游标变量,通过游标变量提高效率
遍历相关的成员函数是相互依赖,相互配合的关系
封装结点的申请和删除操作更有利于增强扩展性