namespace LinkListTest
{
template <typename T> class Node
{
public:
Node(const T& data, Node<T>* next) : _data(data), _next(next)
{}
T GetData() const
{
return _data;
}
Node<T>* GetNext() const
{
return _next;
}
void SetNext(Node<T>* next)
{
_next = next;
}
private:
T _data;
Node<T>* _next;
};
template <typename T> class LinkList
{
public:
LinkList(int count, Node<T>* head) : _count(count), _head(head)
{
}
void InsertBeforeHead(const T& data)
{
Node<T>* node = new Node<T>(data, _head);
_head = node;
++_count;
}
void Insert(Node<T>* const & afterMe, const T& data)
{
Node<T>* node = new Node<T>(data, afterMe->GetNext());
afterMe->SetNext(node);
++_count;
}
void Display()
{
Node<T>* here = _head;
while (here)
{
cout << here->GetData() << endl;
here = here->GetNext();
}
}
bool IsFound(const T& target)
{
Node<T>* here = _head;
while (here && (here->GetData() != target))
/*不能写为 ((here->GetData() != target) && here )因为here可能为空,here->GetData() 会出现非法访问,注意指针的有效性。循环条件是复合条件时将最先不满足的条件放在前面*/
{
here = here->GetNext();
}
if (NULL == here)/*此处也不能用(here->GetData() == target),因为here可能为空,出现非法访问*/
return false;
else
return true;
//也可写成
/*while (here)
{
if (here->GetData() == target)
return true;
here = here->GetNext();
}
return false;*/
}
private:
int _count;
Node<T>* _head;
};
}
/*以下是将Node定义为内部结构,防止外部使用*/
namespace LinkListTest
{
template <typename T> class LinkList
{
public:
template <typename T1> class Node;//前向声明
LinkList(int count, Node<T>* head) : _count(count), _head(head)
{
}
void InsertBeforeHead(const T& data)
{
Node<T>* node = new Node<T>(data, _head);
_head = node;
++_count;
}
void Insert(Node<T>* const & afterMe, const T& data)
{
Node<T>* node = new Node<T>(data, afterMe->GetNext());
afterMe->SetNext(node);
++_count;
}
void Display()
{
Node<T>* here = _head;
while (here)
{
cout << here->GetData() << endl;
here = here->GetNext();
}
}
bool IsFound(const T& target)
{
Node<T>* here = _head;
while (here && (here->GetData() != target))
{
here = here->GetNext();
}
if (NULL == here)
return false;
else
return true;
}
int GetCount() const
{
return _count;
}
private:
int _count;
Node<T>* _head;
//将Node定义为内部结构
private:
template <typename T1> class Node
{
public:
Node(const T1& data, Node<T1>* next) : _data(data), _next(next)
{}
T1 GetData() const
{
return _data;
}
Node<T1>* GetNext() const
{
return _next;
}
void SetNext(Node<T1>* next)
{
_next = next;
}
private:
T1 _data;
Node<T1>* _next;
};
};
}