数据结构基础(11) --循环链表的设计与实现(二)
2015-01-26 23:10:37
·
作者:
·
浏览: 26
//ListIterator 除了判空函数的判空条件之外, 没有任何改变 template
class ListIterator { public: ListIterator(const MyList
&_list): list(_list), currentNode((_list.first)->next) {} //重载 *operator const Type &operator*() const throw (std::out_of_range); Type &operator*() throw (std::out_of_range); //重载 ->operator const Node
*operator->() const throw (std::out_of_range); Node
*operator->() throw (std::out_of_range); //重载 ++operator ListIterator &operator++() throw (std::out_of_range); //注意:此处返回的是值,而不是reference ListIterator operator++(int) throw (std::out_of_range); bool isEmpty() const; private: const MyList
&list; Node
*currentNode; }; template
bool ListIterator
::isEmpty() const { // ++ 注意:判空条件改为list.first if (currentNode == list.first) return true; return false; } template
const Type &ListIterator
::operator*() const throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range(iterator is out of range); // 返回当前指针指向的内容 return currentNode->data; } template
Type &ListIterator
::operator*() throw (std::out_of_range) { //首先为*this添加const属性, //以调用该函数的const版本, //然后再使用const_case, //将该函数调用所带有的const属性转除 //operator->()的non-const版本与此类同 return const_cast
( static_cast
&>(*this).operator*() ); } template
const Node
*ListIterator
::operator->() const throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range(iterator is out of range); //直接返回指针 return currentNode; } template
Node
*ListIterator
::operator->() throw (std::out_of_range) { // 见上 return const_cast
*> ( static_cast
>(*this).operator->() ); } template
ListIterator
&ListIterator
::operator++() throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range(iterator is out of range); //指针前移 currentNode = currentNode->
next; return *this; } template
ListIterator
ListIterator
::operator++(int) throw (std::out_of_range) { ListIterator tmp(*this); ++ (*this); //调用前向++版本 return tmp; } #endif // MYLIST_H_INCLUDED
?
附-测试代码:
int main()
{
MyList
iMyList;
for (int i = 0; i < 10; ++i) //1 2 3 4 5 6 7 8 9 10
iMyList.insert(i+1, i+1);
for (int i = 0; i < 5; ++i) //40 30 20 10 0 1 2 3 4 5 6 7 8 9 10
iMyList.insertFront(i*10);
iMyList.insertFront(100);//100 40 30 20 10 0 1 2 3 4 5 6 7 8 9 10
iMyList.remove(10); //100 40 30 20 0 1 2 3 4 5 6 7 8 9
iMyList.remove(8); //100 40 30 20 0 1 2 3 4 5 6 7 9
cout << ------------ MyList ------------ << endl;
for (ListIterator
iter(iMyList); !(iter.isEmpty()); ++ iter) cout << *iter << ' '; cout << endl; cout << Test: << iMyList << endl; return 0; }