数据结构复习之 顺序表的C++实现

这部分学的时候由于自己刚转专业 确实也没什么编程基础 几个实验做起来也是稀里糊涂 虽然原理课上都听懂了 具体实现的时候还是一脸懵 所以正好自己复习数据结构 就来再实现一遍

这次先实现顺序表,实现的具体功能包括:头插 头删 插入具体位置 删除具体位置元素 输出所有元素 按值搜索 按位置搜索

由于之前做的就是基于模板来实现的 这里也这样实现 实话实说现在看来当时学的东西真的没有那么难

代码具体实现

#include 
using namespace std;
/*设定顺序表最长长度100*/
const int MaxSize = 100;
//顺序表类 
template
class SqList
{
	public:
		SqList(){};
		SqList(ElemType a[],int len);
		~SqList(){};
		int GetLength(){return length;};
		//获取位置i的元素 
		ElemType GetXElem(int i);
		//指定位置插入 越界:<0 头插 >length  尾插 
		void InsertElem(ElemType x,int pos);
		//头插 
		void HeadInsert(ElemType x);
		//头删 
		void HeadDelete();
		// 删除某位置元素 
		void DeleteElem(int pos);
		//输出所有元素 空格分开
		int LocateElem(int x);
		void PrintElem(); 
	private:
		ElemType data[MaxSize];
		int length;
};
//带参构造函数
template 
SqList::SqList(ElemType a[],int len)
{
	if(len>MaxSize)
		cout<<"too many elems"<
ElemType SqList::GetXElem(int pos)
{
	if(pos<0 || pos>=length)
		cout<<"Position Error"<
void SqList::InsertElem(ElemType x,int pos) 
{
	if(pos<0)
	{
		cout<<"position<0 ,Head Insert"<=0;i--)
		{
			data[i+1] = data[i];
		}
		data[0] = x;
		length++;
	}
	else if(pos>=length)
	{
		cout<<"position>length-1,Tail Insert"<=pos;i--)
		{
			data[i+1] = data[i];
		}
		data[pos] = x;
		length++;
	}
}
//头插
template
void SqList::HeadInsert(ElemType x)
{
	for(int i = length-1;i>=0;i--)
		data[i+1] = data[i];
	data[0] = x;
	length++;
 } 
//头删
template
void SqList::HeadDelete()
{
	for(int i=1;i
void SqList::DeleteElem(int pos)
{
	for(int i=pos;i
void SqList::PrintElem()
{
	for(int i=0;i
int SqList::LocateElem(int x)
{
	int pos;
	for(int i=0;isq = SqList(a,10);
	sq.PrintElem();
	cout<<"Please Input Your Choice"<>c && c<=6)
	{
		if(c == 1)
		{
			int x;
			cout<<"Please input elem"<>x;
			sq.HeadInsert(x);
			sq.PrintElem();
		}
		if(c==2)
		{
			sq.HeadDelete();
			sq.PrintElem();
		}
		if(c==3)
		{
			int x,pos;
			cout<<"please input elem and position"<>x>>pos;
			sq.InsertElem(x,pos);
			sq.PrintElem();
		}
		if(c==4)
		{
			int pos;
			cout<<"please input the position to delete"<>pos;
			sq.DeleteElem(pos);
			sq.PrintElem();
		}
		if(c==5)
		{
			int pos;
			cout<<"please input the position to search"<>pos;
			cout<>x;
			cout<

实验效果

数据结构复习之 顺序表的C++实现_第1张图片

你可能感兴趣的:(考研复习-数据结构)