数据结构(C++)——顺序表(1)

问题描述:

已知顺序表类的定义如下,实现各个成员函数。主函数中输入数据(以0结束)利用Insert函数依次将数据插入到表的1号位置,利用DispList按照逻辑次序输出表中元素,再输入一个要查找的元素,利用查找函数Locate查找其在表中的位置,最后利用Reverse函数将数据逆序,再利用DispList输出。

类的定义:

template <class T>
class SeqList{
       public:
              SeqList(); //构造函数,将表置空
              ~SeqList(){} //析构
              int Locate(T x); //查找元素x在表中的位置,成功返回x在表中的位置,否则返回0
              void Insert(int i, T x); //在表的i位置插入元素x
              void Reverse(); //逆序表中数据
              void DispList();
       private:
              T data[MaxSize];    //存储元素
          int length;              //顺序表实际长度
};

样例输入:

输入样例说明:例如输入数据为:1 2 3 4 5 6 0 3,即将1,2,3,4,5,6插入表中的1号位置,得到逻辑次序为6,5,4,3,2,1的顺序表,3为在表中待查找的数据,3的位置为4。
输入:1 2 3 4 5 6 0 3
输出:
The length:6
The elements:
6 5 4 3 2 1 
Found position:4
The length:6
The elements:
1 2 3 4 5 6 
若查找的数据不存在,则输出:No found

代码实现:

#include<iostream>
using namespace std;
const int MaxSize=100;
template <class T>
class SeqList
{
private:
              T data[MaxSize];    //存储元素
          int length;              //顺序表实际长度
       public:
              SeqList() //构造函数,将表置空
			  {
				  length=0;
				  data[0]=0;
			  }
              ~SeqList(){} //析构
              int Locate(T x) //查找元素x在表中的位置,成功返回x在表中的位置,否则返回0
			  {
				  int i;
				  for(i=0;i<length;i++)
					  {
					  if(data[i]==x)
					  {
						  cout<<"Found position:"<<length-i<<endl;
					  return 0;
					  }
				  }
			  cout<<"No found"<<endl;
				  return 0;
			  }
              void Insert(int i, T x)//在表的i位置插入元素x
			  {
				  int j;
				  if(length>=MaxSize) throw;
				  if(i<1&&i>length+1) throw;
				  for(j=length;j>=i;j--)
					  data[j]=data[j-1];
				  data[i]=x;
				  length++;
				  
			  }

             void Reverse() //逆序表中数据
			 {
				 int i,j,t;
				 for(i=0,j=length-1;i<length/2;i++,j--)
				 {
					 t=data[i];
					 data[i]=data[j];
					 data[j]=t;
				 }
			 }
              void DispList()
			  {
				  cout<<"The length:"<<length<<endl;
				  cout<<"The elements:"<<endl;
				  for(int i=length-1;i>=0;i--)
					 cout<<data[i]<<" ";
				  cout<<endl;
			  }

};
int main()
{
	SeqList<int> L1;
	int i=0,n;
	while(cin>>n&&n)
	{
		L1.Insert(i,n);
		i++;
	}
	double x;
	cin>>x;
		L1.DispList();
	L1.Locate(x);
	L1.Reverse();
	L1.DispList();
	return 0;
}

喜欢就点个赞吧(*^▽^*)

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

了不起的企鹅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值