⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 seqlisttest.cpp

📁 改程序为一个线性表程序
💻 CPP
字号:
#include<iostream>
using namespace std;

const int MaxSize=20; 

template <class Type>              //模板类SeqList
class SeqList
{
public:
	SeqList( );                    //无参数的构造函数
    SeqList( Type a[], int n);     //有参数的构造函数
    ~SeqList();                    //析构函数是空的
    int Length();                  //求线性表的长度
    Type Find( int i);             //Find查找,取线性表的第i个元素
    void Insert( int i, Type x);   //在线性表中第i个位置插入值为x的元素
    Type Remove( int i);           //删除线性表中的第i个元素
    void PrintList();              //遍历线性表,按照序号顺序依次输出各元素
private:
    Type data[MaxSize];            //存放数据元素的数组
    int length;                    //线性表的长度
};

template <class Type> SeqList<Type>:: SeqList( )
{
	length = 0;
}

template <class Type> SeqList<Type>:: SeqList( Type a[], int n)
{
    if ( n > MaxSize) 
		cout<<"超过线性表的长度 ! "<<endl;
    for ( int i= 0;  i< n; i++)  
    data[i] = a[i];
    length = n;
}

template <class Type> SeqList<Type>:: ~SeqList( ){}

template <class Type> void SeqList<Type>::Insert( int i, Type x)
{ 
	int j;
    if ( length >= MaxSize)
		cout<< "超过线性表的长度 ! "<<endl;
    if ( i < 1 || i > length + 1) 
		cout<< "位置"<<endl;
    for ( j = length; j >= i; j--)
		data[j] = data[j-1];        //第j个元素存在数组下标为j-1处
	data[i-1] = x;
	length++;
}


template <class Type> Type SeqList<Type>::Remove( int i)
{ 
	int x,j;
    if ( length == 0) 
		cout<< "线性表的长度应大于0 ! "<<endl;
    if ( i < 1 || i> length)
		cout<< "位置"<<endl;
	x = data[i-1];
    for ( j = i; j < length; j++)
    data[j-1] = data[j];            //此处j已经是元素所在的数组下标
    length--;
    return x;
}

template <class Type> int SeqList<Type>::Length()
{
	 return length;
}

template <class Type> Type SeqList<Type>::Find( int i)
{
	if (i < 1 && i > length) 
		cout<<"查找位置错误 ! "<<endl;
	else 
		return data[i-1];
}

template <class Type> void SeqList<Type>::PrintList()
{
	for(int i = 0; i < length; i++)
		cout<<data[i]<<endl;
}

void main( )
{ 
	SeqList<int> a;                //创建一个空的顺序表
	cout<< "执行插入操作,插入的顺序表a:  "<<endl;
	a.Insert(1,2);
	a.Insert(2,7);
	a.Insert(3,1);
	a.PrintList();
	cout<<endl;
	
	cout<< "顺序表a的长度为:  ";
	cout<<a.Length()<<endl;         //返回单链表长度
	cout<<endl;
	
	cout<< "Find函数查询第1个元素,";
	cout<< "第1个元素为:  "<<a.Find(1)<<endl; //查找顺序表中第一个元素
	cout<<endl;
	
	if( a.Length())
	{
		cout<< "删除第1个元素:  "<<a.Remove(1) <<endl;	   //删除元素2
		cout<< "删除成功后顺序表a的长度为:  "<< a.Length() <<endl;
	}
	else
	{
		cout<< "顺序表a长度为0 !"<<endl;
	}
	cout<< "删除成功后顺序表a中的元素还有:  "<<endl;
	a.PrintList();                  //输出删除成功后顺序表a中的所有元素
	cout<<endl;
	
	cout<< "插入两个元素到顺序表a,插入3和2." <<endl;
	cout<< "插入3为第一,插入2为第三: "<<endl;
	cout<< "插入3和2后顺序表a为:  "<<endl;
	a.Insert(1,3);
	a.Insert(3,2);
	a.PrintList();                  //输出插入成功后顺序表a中的所有元素
	cout<<endl;
	cout<<"插入后顺序表a的长度为: ";    
	cout<< a.Length() <<endl;
	cout<<endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -