重点内容
用C++实现单链表, 仅仅自己练手之作
下面是一个简单的代码实现
#include <iostream>
using namespace std;
class Clist
{
public:
Clist()
{
mphead = new Node();
}
~Clist()
{
Node *p = mphead;
while (mphead != NULL)
{
mphead = mphead->mpnext;
delete p;
p = mphead;
}
}
void insert(int data) //头插法
{
Node *p = new Node(data);
p->mpnext = mphead->mpnext;
mphead->mpnext = p;
}
void show()
{
Node *p = mphead->mpnext;
while (p != NULL)
{
cout << p->mdata << " ";
p = p->mpnext;
}
cout << endl;
}
private:
class Node
{
public:
Node(int data = 0) : mdata(data), mpnext(NULL){}
int mdata; //数据域
Node *mpnext; //指针域
};
Node *mphead;
};
int main()
{
Clist test;
test.insert(1);
test.insert(2);
test.insert(3);
test.show();
return 0;
}