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

来源:互联网 发布:淘宝淘宝联盟怎么用法 编辑:程序博客网 时间:2024/06/13 22:09

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

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