您的位置:首页 > 编程语言 > C语言/C++

基于C++模板 单链表基本操作

2017-03-16 19:10 344 查看
涵盖单链表的基本操作方法,如有不足,欢迎提意见!

list.h

#ifndef _LIST_H_
#define _LIST_H_

/*节点类*/

template<class T>
class Node
{
public:
T data;
Node* node;
};
/*链表类*/
template<class T>
class List
{
private:
Node* head; //头节点
public:
List (T a);
T GetHeadVal(); //获取链表首部值
T GetTailVal(); //获取链表尾部值
void Add(T a); //在链表尾部添加元素
void Insert(T a); //插入一个链表
int Find(T val) ; //获得有此值的链表的索引号
bool IsEmpty(); //判断链表是否为空
int Size() ; //返回链表总元素个数
void show(); //打印链表中元素
~List();
};

#endiflist.cpp
#include"list.h"
#include<iostream>

using namespace std;

/*构造函数*/

template<class T>
List::List(T a)
{
head = new Node;
head->data=a;
head->node=NULL;
}
/*获得首链表的值*/

template<class T>
T List::GetHeadVal()
{
T p=head->data;
return p;
}
/*获得链表末尾元素的值*/

template<class T>
T List::GetTailVal()
{
Node* current=head;
for(;current;current=current->node)
{
;
}
return (current->data);
}
/*在链表中插入元素*/
template<class T>
void List::Insert(T a)  //在索引为pos位置添加元素
{
Node* listnode = new Node;
listnode->data=a;
listnode->node=head->node;
head->node=listnode;
}
/*获得有此值的链表的索引号*/
template<class T>
int  List::Find(T val)
{
Node* current =head;
int num = 0;
for(;current;current = current->node)
{
if(current->data == val)
{
break;
}
num ++;
}
return num;

}
/*判断链表是否为空*/
template<class T>
bool List::IsEmpty()
{
bool result=false;
if(head->node == NULL)
{
result=true;
}
return result;
}
/*在链表尾部插入元素*/
template<class T>
void List::Add(T a)
{
Node* newnode= new Node;
while(head->node)
{
head->node=head->node->node;
}
head->node = newnode;
newnode->node=NULL;
newnode->data=a;
}
/*返回链表总元素个数*/
template<class T>
int List::Size()
{
Node *p=head;
int count=0;
for(;p;p=p->node)
count++;
return count;
}
/*打印链表中数据元素*/
template<class T>
void List::show()
{

for(Node* current = head;current;current=current->node)
{
cout<<"list ="<<current->data<<endl;
}
}
/*析构,清空链表*/
template<class T>
List::~List()
{
Node* p= head;
while(p)
{
Node* q =p->node;
delete p;
p=q;
}
}
main.cpp
#include"list.h"
#include<iostream>

using namespace std;

int main()
{
List<int>list(1);
list.Add(2);
list.Insert(0);
list.Insert(10);
list.Insert(20);
list.show();
cout<<endl<<endl;
cout<<"size ="<<list.Size()<<endl;
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: