C++链表写成类,用起来多轻盈

前言

写一个普通的单链表模板类。将链表结点的增加、销毁等功能封装成接口。

#include <iostream>
using namespace std;

////单链表类模板

template<class T>
class  list
{
public:
	list(T d)//赋值
	{
		data = d;
		next = NULL;
	}
	void add(list * node)//增加一个 node 节点
	{
		node->next = this;
		next = NULL;
	}
	list * getnext() { return next; }//返回一个结点
	T getdata() { return data; }//返回一个 data 值
	void destroy() {
		if (this != NULL) {
			delete this;
			next = NULL;
		}
	}

private:
	T  data;
	list * next;
};

void MyPrint_Interface(list<char>* _list) {
	//显示链表
	list<char>* p = _list;
	while (p)
	{
		std::cout << p->getdata();
		p = p->getnext();//返回一个节点并后移指针
	}
}

void main()
{

	list<char> start('a');//给一个头结点的值
	list<char> *p, *last;



	//建立链表
	last = &start;//last 指向第一个节点('a')
	for (int i = 1; i < 26; i++)
	{
		p = new  list<char>('a' + i);//1.开辟内存       2.赋值
		p->add(last);//连接
		last = p;//移动指向
	}


	//显示
	MyPrint_Interface(&start);
	

	//销毁链表
	list<char> *pCurrent = (&start)->getnext();
	while (pCurrent) {
		p = pCurrent->getnext();
		pCurrent->destroy();
		pCurrent = p;
	}

	//检查
	MyPrint_Interface(&start);

	
	system("pause");

}

猜你喜欢

转载自blog.csdn.net/weixin_41374099/article/details/88374037