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

涵盖单链表的基本操作方法,如有不足,欢迎提意见!

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();
};

#endif
list.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; 
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值