热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C++模板实现的单向链表

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

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 >&#61; m_nLength){cout<<"The position to insert out of range"<next;cnt&#43;&#43;;}Node *pNew &#61; new Node(e);pNew->next &#61; ptr->next;ptr->next &#61; pNew;m_nLength&#43;&#43;;return true;}
}template bool Lists::add(Type e)
{Node *pNew &#61; new Node(e);if (pNew &#61;&#61; NULL){cout<<"allocate memory for new node failed"<next !&#61; NULL){ptr &#61; ptr->next;}ptr->next &#61; pNew;pNew->next &#61; NULL;m_nLength&#43;&#43;;return true;}
}template bool Lists::erase(int pos)
{if (pos >&#61; m_nLength){cout<<"The position to delete out of range"<next;i&#43;&#43;;}Node *pdel &#61; ptr->next;ptr->next &#61; ptr->next->next;delete pdel;pdel &#61; NULL;m_nLength--;return true;}
}template void Lists::print()
{if(m_nLength &#61;&#61;0)cout<<"The list is empty"<next!&#61; NULL){ptr &#61; ptr->next;cout<<"element value:"<e<}template int Lists::getLength()
{return m_nLength;
}
template bool Lists::isEmpty()
{return m_head->next &#61;&#61; NULL;
}template void Lists::clear()
{Node *ptr &#61; m_head->next;Node *ptmp &#61; NULL;while(ptr !&#61; NULL){ptmp &#61; ptr;ptr &#61; ptr->next;delete ptmp;ptmp &#61; NULL;m_nLength--;}m_head->next &#61; NULL;}
template Lists::~Lists()
{Node *ptr &#61; m_head;Node *ptmp &#61; NULL;while(ptr->next !&#61; NULL){ptmp &#61; ptr;ptr &#61; ptr->next;delete ptmp;ptmp &#61; NULL;}delete ptr;ptr &#61; NULL;
}
#endif


//main.cpp

#include
#include "Lists.h"
using namespace std;
void main()
{cout<<"*************************Test list init***************************"< Lisa;cout<<"List&#39;s length is:"<}


程序运行结果&#xff1a;






推荐阅读
author-avatar
阿加芬散阿加芬散
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有