1. 程式人生 > >信管117135張志海資料結構一

信管117135張志海資料結構一

標頭檔案如下 #ifndef SeqList_H                            //避免重複包含SeqList.h標頭檔案
#define SeqList_H
const int MaxSize=10;                         //線性表最多包含10個元素
class SeqList
{
public:
 SeqList(){length=0;}                      //無參建構函式,建立一個空表
 SeqList(int a[],int n);                   //有參建構函式
 ~SeqList(){}                              //解構函式
 void Insert(int i,int x);                 //線上性表第i個位置插入值為x的元素
 int Delete(int i);                        //刪除線性表的第i個位置
 int Locate(int x);                        //求線性表中值為x的元素序號
 void PrintList();                         //按序號依次輸出各元素
private:
 int data[MaxSize];                        //存放資料元素的陣列
 int length;                               //線性表的長度
};
#endif
以下為SeqList.cpp檔案

#include<iostream>                                        //引入輸入輸出流
using namespace std;                                     
#include"SeqList.h"                                       //引入類SeqList的宣告 
                                                          //以下是類SeqList的成員函式的定義
SeqList::SeqList(int a[],int n)
{
 if(n>MaxSize)throw"引數非法";
 for(int i=0;i<n;i++)
  data[i]=a[i];
 length=n;
}
void SeqList::Insert(int i, int x)
{
 if(length>=MaxSize)throw"上溢";
 if(i<1||i>length+1)throw"位置非法";
 for(int j=length;j>=i;j--)
  data[j]=data[j-1];                                //第j個元素存放陣列下標為j-1處
 data[i-1]=x;
 length++;
}
int SeqList::Delete(int i)
{
 if(length==0)throw"下溢";
 if(i<1||i>length)throw"位置非法";
 int x=data[i-1];
 for(int j=i;j<length;j++)
  data[j-1]=data[j];                                //此處j已經是元素所在陣列的下標
 length--;
 return x;
} int SeqList::Locate(int x)
{
 for (int i=0;i<length;i++)
  if(data[i]==x)return i+1;                         //下標為i的元素序號為i+1
  return 0;                                         //退出迴圈,說明查詢失敗的原因
}
void SeqList::PrintList()
{
 for(int i=0;i<length;i++)
  cout<<data[i]<<"";
 cout<<endl;
}

以下為SeqList_main.cpp檔案

#include<iostream>                                  //引入輸入輸出流
using namespace std;
#include"SeqList.h"                                 //引入類SeqList的宣告
void main()
{
 int r[5]={1,2,3,4,5};
 SeqList L(r,5);
 cout<<"執行插入操作前的資料為:"<<endl;
 L.PrintList();                                  //輸出所有元素
 try
 {
  L.Insert(2,3);
 }
 catch(char * s)
 {
  cout<<s<<endl;
 }
 cout<<"執行插入操作後資料為:"<<endl;
 L.PrintList();                                  //輸出所有元素
 cout<<"值為3的元素位置為:";
 cout<<L.Locate(3)<<endl;                        //查詢元素3,並返回在順序表中位置
 cout<<"執行刪除第一個元素的操作,刪除前資料為:"<<endl;
 L.PrintList();                                  //輸出所有元素
 try
 {
  L.Delete(1);                                //刪除第一個元素
 }
 catch(char * s)
 {cout<<s<<endl;
 }
 cout<<"刪除後資料為:"<<endl;
 L.PrintList();                                  //輸出所有元素
}