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

本文介绍了如何使用C++实现顺序表数据结构,包括构造、析构、清空、判断空表、压入元素、显示元素、取元素、定位查找、插入、删除、替换等操作。代码中定义了一个Sqlist模板类,支持动态调整表长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*----------sqlist.h----------*/

 

#ifndef SQLIST_H
#define SQLIST_H
//起始下标为 1 
//最大下标为 SIZE
const int SIZE(10);
              //此处修改默认表长大小
template <typename Type> class Sqlist{
public:
 Sqlist(int maxsize=SIZE)
 {
  while(maxsize<1){
   cout << "设置最大表长有误,请重新设置->: " ;
   cin >> maxsize;
  }
  MaxSize=maxsize;
  data=new Type[MaxSize+1]; // data[MaxSize] 为表满状态
  last=0; //空表状态
 }
 ~Sqlist()
 {
  delete [] data;
 }
 void Clear() //清空顺序表
 {
  last=0;
 }
 bool Empty() //判空
 {
  if(last==0)
   return true;
  else
   return false;
 }
 status push_back(const Type &value) //压入(后插)
 {
  if(last==MaxSize){
   cerr << "顺序表已满,操作失败! " << endl;
   return 0;
  }else {
   data[last+1]=value;
   last++;
   return 1;
  }
 }
 void Display() //显示
 {
  for(int i=1;i<=last;i++)
   cout << data[i] << " ";
  cout << endl;
 }
 Type GetElem(int i) //取元素
 {
  if(last==0){
   cerr << "顺序表为空,操作失败! " ;
   goto end;
  }
  if(i<1||i>last){
   cerr << "下标越界,请检查->: ";
   goto end;
  }
  return data[i];
  end:cout << endl;
 }
 int Locate(const Type &value) //定位查找
 {
  if(last==0){
   cerr << "顺序表为空,操作失败!" << endl;
   return 0;
  }
  for(int i=1;i<=last;i++)
   if(data[i]==value)
    return i;
  cerr << "顺序表中没有此元素:" << value << " !" <<endl;
  return 0;
 }
 status Insert(int i,const Type &value) //插入操作
 {
  if(last==MaxSize){
   cerr << "顺序表已满,操作失败!" << endl;
   return 0;
  }
  if(i<1||i>last+1){
   cerr << "插入位置有误,请检查: " << endl;
   return 0;
  }
  for(int j=last;j>=i;j--)
   data[j+1]=data[j];
  data[i]=value;
  last++;
 }
 status Delete(int i) //删除操作
 {
  if(last==0){
   cerr << "顺序表为空,操作失败! " << endl;
   return 0;
  }
  if(i<1||i>last){
   cerr << "下标越界,请检查:" << endl;
   return 0;
  }
  for(int j=i;j<last;j++)
   data[j]=data[j+1];
  last--;
  return 1;
 }
 int length()
 {
  return last;
 }
 int size()
 {
  return last;
 }
 status Replace(int i,const Type &value) //替换
 {
  if(last==0 || i<1 || i > last){
   cerr << "下标越界,操作失败。" << endl;
   return 0;
  }else{
   data[i]=value;
   return 1;
  }
 }
 Type operator [](int i) //重载 []
 {
  if(i<1||i>last||last==0){
   cerr << "下标越界,请检查! " << endl;
   exit(0);
  }else
   return data[i];
 }
  

private:
 Type *data;
 int last;
 int MaxSize;
};

 

#endif

 

//本人正在自学数据结构,欢迎老师批评指正,谢谢关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值