所谓的数据结构很容易学习,我认为关键是在于对指针的概念的深刻理解
链表类一般由操作函数和节点构成,这个节点可以是结构,也可以是一个类
如下
#include "iostream.h"
struct NODE
{
NODE(){Hext = NULL;}//结构的构造函数,可以去掉
int a;
NODE *Hext;//指向下一个
};
class CLsit
{
public:
CLsit();
virtual ~CLsit();
NODE* AddTail(NODE *node);
NODE* AddHead(NODE *node);
NODE* Find(int index);
NODE* InsertAfter(NODE*node, NODE *newNode);
void Printf();
public:
public:
NODE *Head;
NODE *pCurrent;
};
CLsit::CLsit()
{
Head = NULL;
}
CLsit::~CLsit()
{
}
NODE* CLsit::AddTail(NODE *node)
{
if (!Head)
{
Head = node;
pCurrent = node;
}
else
{
pCurrent->Hext = node;
pCurrent = node;
}
return node;
}
NODE* CLsit::AddHead(NODE *node)
{
if (!Head)
{
Head = node;
pCurrent = node;
}
else
{
node->Hext = Head;
Head = node;
}
return node;
}
void CLsit::Printf()
{
NODE *pMed = Head;
while (Head)
{
cout<<Head->a<<endl;
Head = Head->Hext;
}
Head = pMed;
}
NODE* CLsit::Find(int index)
{
int n = 0;
NODE *node = NULL;
NODE *pMed = Head;
if (index == 0)
{
return Head;
}
for (int i = 0; i < index; i++)
{
node = pMed->Hext;
pMed = pMed->Hext;
}
return node;
}
NODE* CLsit::InsertAfter(NODE*node, NODE *newNode)
{
if (!node)
{
return AddTail(newNode);
}
else
{
NODE *pMed = node->Hext;
node->Hext = newNode;
newNode->Hext = pMed;
return newNode;
}
}
void main()
{
CLsit list;
NODE * node = new NODE();
node->a = 1;
list.AddTail(node);
NODE* node1 = new NODE();
node1->a = 2;
list.AddTail(node1);
NODE *node2 = new NODE();
node2->a = 3;
list.AddTail(node2);
NODE *node3 = new NODE();
node3->a = 4;
NODE *me = list.Find(1);
list.InsertAfter(me,node3);
list.Printf();
}