基于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();};#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; }
0 0
- 基于C++模板 单链表基本操作
- 基于单链表的列表基本操作 类C语言实现
- C++-----单链表基本操作
- splay模板基本操作
- 基于C API的SQLite3基本数据库操作
- 基于C API的SQLite3基本数据库操作
- 基于C API的SQLite3基本数据库操作
- 嵌入式 基于C API的SQLite3基本数据库操作
- 基于C API的SQLite3基本数据库操作
- 基于C API的SQLite3基本数据库操作
- 【基本数据结构】C语言基于数组的栈操作
- 【C++】单链表的基本操作
- C语言单链表基本操作
- 基于SpringMVC基本操作
- 基于二叉排序树的基本操作
- 基于C文件操作
- 单链表基本操作c语实现
- c语言单链表的基本操作(代码)
- Java 字符流操作
- 第四周:( LeetCode417 ) Pacific Atlantic Water Flow(c++)
- JS实现弹出框文字居中
- 实现应用软件能够通过运行窗口打开
- Java抽象类
- 基于C++模板 单链表基本操作
- linux下使用ffmpeg将amr转成mp3
- Math.round(11.5)等于多少?Math.round(-11.5)等于多少?
- Linux Centos安装python相关库失败处理方法
- linux进程间通信———内存共享
- Spring Cloud 基于eureka 服务注册中心
- JAVA利用SSH2登录LINUX并执行命令
- 1009. 说反话 (20) python篇
- android-奇异bug:parameter must be a descendant of this view