#ifndef _LIST_H
#define _LIST_H
// 循环列表,
template<class Type> class List;
template<class Type> class ListIterator;
template<class Type>
class ListNode
{
friend class List<Type>;
friend class ListIterator<Type>;
private:
Type data; // 节点里的数据,
ListNode *link; // 指向下一个节点的数据,
ListNode(Type);
ListNode(){}
};
template<class Type>
class List
{
friend class ListIterator<Type>;
public:
List() { first = new ListNode<Type>; first->link = first; } // 这是一个标头结构,
void Delete(Type);
void Insert(Type);
private:
ListNode<Type> *first;
};
template<class Type>
class ListIterator
{
public:
ListIterator(const List<Type>& l):list(l),current(l.first->link){}
bool NotNull();
bool NextNotNull();
Type* First();
Type* Next();
private:
const List<Type> &list;
ListNode<Type>* current;
};
template<class Type>
bool ListIterator<Type>::NotNull()
{
if(current != list.first) return true;
else return false;
}
template<class Type>
bool ListIterator<Type>::NextNotNull()
{
if(current->link != list.first) return true;
else return false;
}
template<class Type>
Type* ListIterator<Type>::First()
{
if(current != list.first) return ¤t->data;
else return 0;
}
template <class Type>
Type* ListIterator<Type>::Next()
{
current = current->link;
if(current == list.first) current = current->link;
return ¤t->data;
}
template<class Type>
ListNode<Type>::ListNode(Type element)
{
data = element; // 参数就是节点里的数据放到data里边,
link = 0;
}
template<class Type>
void List<Type>::Insert(Type k)
{
ListNode<Type> *newnode = new ListNode<Type>(k);
newnode->link = first->link; // 新的节点作为第一个节点的标头,标头就是循环链表的开始
first->link = newnode;
}
template<class Type>
void List<Type>::Delete(Type k)
{
ListNode<Type> *previous = first; // 前一个,
ListNode<Type> *current;
for(current = first->link;
(current != first) && current->data != k;
previous = current, current = current->link)
{
;// 什么都不做,空循环,找到要被删除的节点,
}
if(current != first) // first是空的,
{
previous->link = current->link;
delete current;
}
}
#endif _LIST_H
#include <iostream>
#include "List.h" //这个是自己做的链表,
#include <list> // C++ STL中的链表
using namespace std;
int main()
{
cout << "这是自己设计的链表和迭代器:" << endl;
List<int> intList;
intList.Insert(31);
intList.Insert(12);
intList.Insert(3);
intList.Insert(6);
ListIterator<int> li(intList);
if(li.NotNull())
{
cout << *li.First(); // 在迭代的过程中可以进行操作,
while(li.NextNotNull())
cout << " -> " << *li.Next();
cout << endl;
}
cout << "测试一下循环:" << endl;
ListIterator<int> iter(intList);
cout << *iter.First() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
cout << *iter.Next() << endl;
return 0;
}