频道栏目
首页 > 程序开发 > 软件开发 > C++ > 正文
C++ 模板实现的单向链表
2014-02-27 11:34:41         来源:C++ 模板实现的单向链表  
收藏   我要投稿

C++模板实现的单向链表,实现了链表的初始化创建,元素插入,元素链表末尾添加,元素删除,链表清空

//Lists.h

#ifndef DDXXLISTS_H
#define DDXXLISTS_H
#include 
using namespace std;
template
class Lists
{
public:
	Lists();
	Lists(int nSize);
	~Lists();
public:
	struct Node
	{
		Type  e;
		Node* next;
		Node()
		{
		}
		Node(Type _e)
		{
			e = _e;
			next = NULL;
		}
	};
public:
	bool insert(Type e,int pos);
	bool add(Type e);
	bool erase(int pos);
	void clear();
	bool isEmpty();
	int getLength();
	void print();
private:
	Node* m_head;
	int m_nLength;
};

template Lists::Lists()
{
	Node *pPos = new Node;
	pPos->next = NULL;
	m_head = pPos;
	m_nLength = 0;
}

template Lists::Lists(int nSize)
{
	m_nLength = nSize;
	Node *pPos = new Node;
	pPos->next = NULL;
	m_head = pPos;
	m_nLength = nSize;
	
	for (int i=0;inext = new Node;
		pPos = pPos->next;
	}
}

template bool Lists::insert(Type e,int pos)
{
	if (pos >= m_nLength)
	{
		cout<<"The position to insert out of range"<next;
			cnt++;
		}
		Node *pNew = new Node(e);
		pNew->next = ptr->next;
		ptr->next = pNew;

		m_nLength++;
		return true;
	}
}

template bool Lists::add(Type e)
{
	Node *pNew = new Node(e);
	if (pNew == NULL)
	{
		cout<<"allocate memory for new node failed"<next != NULL)
		{
			ptr = ptr->next;
		}
		ptr->next = pNew;
		pNew->next = NULL;
		m_nLength++;
		return true;
	}
}

template bool  Lists::erase(int pos)
{
	if (pos >= m_nLength)
	{
		cout<<"The position to delete out of range"<next;
			i++;
		}
		Node *pdel = ptr->next;
		ptr->next = ptr->next->next;
		delete pdel;
		pdel = NULL;
		m_nLength--;

		return true;
	}
}

template void Lists::print()
{
	if(m_nLength ==0)
		cout<<"The list is empty"<next!= NULL)
	{
		ptr = ptr->next;
		cout<<"element value:"<e< int Lists::getLength()
{
	return m_nLength;
}
template bool Lists::isEmpty()
{
	return m_head->next == NULL;
}

template void Lists::clear()
{
	Node *ptr = m_head->next;
	Node *ptmp = NULL;
	while(ptr != NULL)
	{
		ptmp = ptr;
		ptr = ptr->next;
		delete ptmp;
		ptmp = NULL;
		m_nLength--;
	}
	m_head->next = NULL;

}
template Lists::~Lists()
{
	Node *ptr = m_head;
	Node *ptmp = NULL;
	while(ptr->next != NULL)
	{
		ptmp = ptr;
		ptr = ptr->next;
		delete ptmp;
		ptmp = NULL;
	}
	delete ptr;
	ptr = NULL;
}
#endif

//main.cpp

#include 
#include "Lists.h"
using namespace std;
void main()
{
	cout<<"*************************Test list init***************************"< Lisa;
	cout<<"List's length is:"<
程序运行结果:





点击复制链接 与好友分享!回本站首页
相关TAG标签 C++ 单向 模板
上一篇:Remove Duplicates from Sorted Array -- LeetCode
下一篇:C++ std::thread的坑
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站