C++线性表
来源:互联网 发布:python 文本分类 编辑:程序博客网 时间:2024/06/06 02:26
//SeqList.h#define MaxSize 100template <class DataType>class SeqList{ private: DataType data[MaxSize]; //存放数据元素的数组 int length; //线性表的长度 public: SeqList(){length=0;} //构建一个空顺序表 SeqList(DataType a[],int n); //构造一个长度为n的顺序表 ~SeqList(){} //析构函数 int Length(){return length;} //求线性表长度 DataType Get(int i); //取线性表中第i个元素 int Locate(DataType x); //取线性表中值为x的元素的序号 void Insert(DataType x,int i); //插入操作,在i插入x DataType Delete(int i); //删除操作,删除第i个元素 void PrintList(); //遍历操作,输出个元素};//构造一个长度为n的顺序表template <class DataType>SeqList<DataType>::SeqList(DataType a[],int n){ if (n>MaxSize) throw "参数非法"; for (int i=0;i<n;i++) { data[i]=a[i]; } length=n;}//按位查找template <class DataType>DataType SeqList<DataType>::Get(int i){ if (i<1&&i>length) throw "位置非法"; else return data[i-1];}//按值查找template <class DataType>int SeqList<DataType>::Locate(DataType x){ for (int i=0;i<length;i++) { if (data[i]==x) return i+1; } return 0; //查找失败}//删除template <class DataType>DataType SeqList<DataType>::Delete(int i){ DataType x; if (length==0) throw "下溢"; if (i<1&&i>length) throw "位置非法"; x=data[i-1]; for (;i<length;i++) { data[i-1]=data[i]; } length--; return x;}//插入template <class DataType>void SeqList<DataType>::Insert(DataType x,int i){ if (i>MaxSize) throw "上溢"; if (i<1&&i>length) throw "位置非法"; for (int j=length;j>=i;j--) { data[j]=data[j-1]; data[j-1]=x; } length++;}//遍历template <class DataType>void SeqList<DataType>::PrintList(){ cout<<"当前线性表为:"<<endl; for (int i=0;i<length;i++) { cout<<data[i]<<'\t'; } cout<<endl;}
//main.cpp#include <iostream>#include "SeqList.h"using namespace std;void main(){ int a[10]={2,5,4,8,9,1,3,7,6,0}; //测试数组 //顺序表 cout<<"初始化线性表"<<endl; SeqList<int> sl(a,10); sl.PrintList(); cout<<sl.Length()<<endl; cout<<"获取i位元素"<<endl; cout<<sl.Get(3)<<endl; cout<<"i位插入元素x"<<endl; sl.Insert(10,5); sl.PrintList(); cout<<sl.Length()<<endl; cout<<"值为x的元素"<<endl; cout<<sl.Locate(6)<<endl; cout<<"删除i位元素"<<endl; cout<<sl.Delete(8)<<endl; sl.PrintList(); sl.Length();}
1 0
- 线性表(C++)
- 数据结构-线性表 (C++)
- Objective-C 线性表
- 数据结构线性表c
- 线性顺序表C
- 线性链表C
- 线性表--单链表(C++)
- C - 数据结构 - 线性表
- C线性表
- 线性表 C
- 线性表(C++)
- 线性表(C++)
- C构造线性表
- C语言-线性表
- c 线性链表程序
- C语言实现线性表
- c语言线性表详解
- 线性表 C语言实现
- JSONObject put,accumulate,element的区别
- Android4.4 xposed安装失败(the xposed framework is not installed)
- js中几种实用的跨域方法原理详解
- 为RecyclerView精确的添加Click及LongClick事件
- 5.7 mysqldump 问题
- C++线性表
- Mysql高并发优化
- uboot目录结构分析
- 应用获取Power Key/Home Key按键事件(framework层)
- Unity3D 零碎知识点集合 (持续更新)
- 关于set想说的(二)之Set Demo
- 【bzoj3672】[Noi2014]购票 斜率优化+树链剖分+线段树+凸包+三分
- Python 数据结构与算法——快排
- linux java 环境变量配置