1. 程式人生 > >順序表的基本操作(C++)

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

// 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位置插入值x void 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):