闲来无事写的,其实现了一个双向环形链表模板类,其中NODE节点类中的数据块使用了指针类型,这样就可以向链表添加各种各样的对象了,比如将其自身作为类型添加进去就可以实现类似二维矩阵的结构,此类仅实现了链表的部分方法,由于对C++了解有限,其中的问题非常希望大家能给予指正。
/*
* File: BidCircleList.h
* Author: haifeng
*
* Created on 2016年2月28日, 上午9:29
*/
#ifndef BIDCIRCLELIST_H
#define BIDCIRCLELIST_H
template<typename N>
class NODE {
public:
N *DATA;
NODE<N> *p_NEXT;
NODE<N> *p_PRE;
public:
NODE()
{
p_NEXT = 0;
p_PRE = 0;
}
NODE(N *data)
{
DATA = data;
p_NEXT = 0;
p_PRE = 0;
}
};
template<typename N>
class BidCircleList {
private:
NODE<N> *p_head;
NODE<N> *p_current;
int nodenum;
public:
BidCircleList()
{
p_head = new NODE<N>();
p_head->p_PRE = p_head;
p_head->p_NEXT = p_head;
p_current = p_head;
nodenum = 0;
}
~BidCircleList()
{
Clear();
delete p_head;
}
void Insert(N* data);
void Clear();
bool IsNull();
int Count() const;
N* GetData() const;
void SetData(N data);
bool MoveNext();
bool MovePrevious();
void MoveToHead();
bool Remove();
NODE<N>* SearchNode(N* data);
};
template<typename N>
void BidCircleList<N>::Insert(N *data)
{
NODE<N> *newnode = new NODE<N>(data);
newnode->p_NEXT = p_current->p_NEXT;
newnode->p_PRE = p_current;
p_current->p_NEXT = newnode;
newnode->p_NEXT->p_PRE = newnode;
nodenum++;
};
template<typename N>
bool BidCircleList<N>::Remove()
{
if (p_current == p_head) {
return false;
}
NODE<N> *p_temp = p_current->p_NEXT;
p_current->p_PRE->p_NEXT = p_current->p_NEXT;
p_current->p_NEXT->p_PRE = p_current->p_PRE;
delete p_current;
p_current = p_temp;
nodenum--;
return true;
};
template<typename N>
void BidCircleList<N>::Clear()
{
MoveToHead();
if (MoveNext()) {
while (Remove()) {
}
}
};
template<typename N>
bool BidCircleList<N>::IsNull()
{
if (nodenum == 0) {
return true;
}
return false;
};
template<typename N>
int BidCircleList<N>::Count() const
{
return nodenum;
};
template<typename N>
N* BidCircleList<N>::GetData() const
{
return p_current->DATA;
};
template<typename N>
void BidCircleList<N>::SetData(N data)
{
*p_current->DATA = data;
};
template<typename N>
bool BidCircleList<N>::MoveNext()
{
if (p_current->p_NEXT == p_head) {
return false;
}
p_current = p_current->p_NEXT;
return true;
};
template<typename N>
bool BidCircleList<N>::MovePrevious()
{
if (p_current->p_PRE == p_head) {
return false;
}
p_current = p_current->p_PRE;
return true;
};
template<typename N>
void BidCircleList<N>::MoveToHead()
{
p_current = p_head;
};
template<typename N>
NODE<N>* BidCircleList<N>::SearchNode(N* data)
{
MoveToHead();
while (MoveNext()) {
if (GetData() == data) {
return p_current;
}
}
return 0;
};
#endif /* BIDCIRCLELIST_H */
本文介绍了一个用C++实现的双向环形链表模板类,该类允许添加各种类型的对象,并提供了基本的操作方法,如插入、删除、移动等。
381

被折叠的 条评论
为什么被折叠?



