这个链表用了个模板类,用起来更方便,原出处:https://codebus.cn/jihe/pvz
template<class T>
class Node
{
public:
T* content;
Node* next = NULL;
Node(T* t)
{
content = t;
}
};
template<class T>
class LinkList
{
public:
Node<T>* head;
Node<T>* tail;
LinkList()
{
head = NULL;
tail = NULL;
};
LinkList(Node<T> node)
{
head = node;
tail = node;
};
~LinkList()
{
DeleteAllNode();
}
void InsertNode(T* t)
{
Node<T>* node=new Node<T>(t);
if (head == NULL)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
};
void DeleteNode(int No)
{
Node<T>* cur = head,*pre=NULL;
while (cur != NULL && cur->content->No != No)
{
pre = cur;
cur = cur->next;
}
if (pre == NULL)
{
head = cur->next;
}
else if (cur == NULL)
{
cout << "没有找到符合条件的结点!" << endl;
return;
}
else
{
pre->next = cur->next;
}
if (cur == tail)
{
tail = pre;
}
delete cur;
};
void DeleteAllNode()
{
Node<T>* cur = head,*pre=NULL;
while (tail != NULL)
{
pre = cur;
cur = cur->next;
DeleteNode(pre->content->No);
}
};
};
下面这个是我之前写的:
// 物体类(链表)
class Object
{
public:
Object(RECT pRct = { 0,0,0,0 })
{
SetRct(pRct);
SetParent(NULL);
SetNext(NULL);
}
RECT GetRct()
{
return rct;
}
void SetRct(RECT pRct)
{
rct = pRct;
}
Object* GetParent()
{
return pParent;
}
void SetParent(Object* parent)
{
pParent = parent;
}
Object* GetNext()
{
return pNext;
}
void SetNext(Object* next)
{
pNext = next;
}
// 得到链表头结点
Object* GetHead()
{
Object* p = this;
while (p->GetParent() != NULL)
p = p->GetParent();
return p;
}
// 得到链表尾节点
Object* GetLast()
{
Object* p = this;
while (p->GetNext() != NULL)
p = p->GetNext();
return p;
}
// 得到节点总数
int GetNum()
{
Object* p = GetHead();
int num = 0;
while (p->GetNext() != NULL)
{
p = p->GetNext();
num++;
}
return num;
}
// 得到链表中的第n个节点的地址
Object* GetAt(int n)
{
if (n > GetNum())
{
return NULL;
}
Object* p = GetHead();
for (int i = 0; i < n; i++)
{
p = p->GetNext();
}
return p;
}
// 创建新节点
// 返回新节点的指针
Object* AddNode(RECT pRct = { 0,0,0,0 })
{
Object* pNode = new Object;
Object* p = GetLast();
p->SetNext(pNode);
pNode->SetParent(p);
pNode->SetRct(pRct);
return pNode;
}
// 插入节点到n位置后
// 返回新节点的指针
Object* Insert(int n, RECT pRct = { 0,0,0,0 })
{
Object* p = new Object;
if (n > GetNum() || n < 0)
{
return NULL;
}
if (n != GetNum())
p->SetNext(GetAt(n)->GetNext());
p->SetParent(GetAt(n));
GetAt(n)->SetNext(p);
p->SetRct(pRct);
return p;
}
// 删除n位置上的节点
// 返回删除是否成功
bool Delete(int n)
{
if (n > GetNum() || n < 1)
{
return false;
}
Object* p = GetAt(n);
if (n != GetNum())
p->GetNext()->SetParent(p->GetParent());
p->GetParent()->SetNext(p->GetNext());
delete p;
return true;
}
private:
RECT rct;
Object* pParent;
Object* pNext;
};