顺序表的基本操作(C++)

来源:互联网 发布:大淘客到底是什么软件 编辑:程序博客网 时间:2024/05/18 14:14

// Sequence.cpp : 定义控制台应用程序的入口点。//

#include "stdafx.h"#include "iostream"using namespace std;//错误1,使用cout要加上此句typedef int type;//忘记知识点:定义type好处就是便于以后总体更改数据类型

class SeqList{ type data[100]; int length; int MaxSize;

public: SeqList(){ length=0; }; void SLCreate(int MaxSize);    int Find(type x); void Insert(type x,int i); void Remove(int i); void display(SeqList); };//错误2:每个class定义完后要加分号

//创建顺序表void SeqList::SLCreate(int sz ){ type x;    cout<<"please input the SeqList:"; for(int i=0;i<sz;i++){  cin>>x;       data[i]=x;    length++; } }//找到值x在表中位置int SeqList::Find(type x){

 for(int i=0;i<length;i++){      if(data[i]==x){    return i;   }       }        cout<<"no"<<x<<"in this seqlist\n";   }//在p位置插入值xvoid SeqList::Insert(type x,int p){

 if(p<0||p>length){ cout<<"the p is illegal"; } else{ for(int i=length-1;i>p;i--)   data[i+1]=data[i];     data[p]=x;    length++;  } }//显示顺序表中的所有元素void SeqList::display(SeqList list){

 for(int i=0;i<list.length;i++){  cout<<list.data[i]<<endl; }    }//删除表中位置p上元素void SeqList::Remove(int p){     if(p<0||p>=length){ cout<<"the p is illegal";  }else{   for(int i=p;i<length;i++){  data[i]=data[i+1];     }   length--;  }   }

void main(){    SeqList FirstList; int length,pdelete,pinsert; type dataInsert,dataFind; cout<<"please input the length of the seqlist:\n"; cin>>length; FirstList.SLCreate(length); FirstList.display(FirstList);

 cout<<"please input the data you want to find:"; cin>>dataFind; int postion=FirstList.Find(dataFind);  cout<<"the data's postion is:\n"<<postion<<"\n";  

 cout<<"please input the postion that you want to delete"; cin>>pdelete; FirstList.Remove(pdelete); cout<<"the seqlist after delete is:\n"; FirstList.display(FirstList);

 cout<<"please input the postion that you want to insert"; cin>>dataInsert>>pinsert; FirstList.Insert(dataInsert,pinsert); cout<<"the seqlist after insert is:\n"; FirstList.display(FirstList);

 

}

 


运行结果如下(注意运行时是ctrl+F5):