順序表的實現

實際上只是起到數組的作用,但是還是完成了它的類實現

//Sequence_List.h文件
//順序表類的聲明
//基本操作:初始化、查詢、插入、刪除、打印 
#ifndef SEQUENCE_LIST_H
#define SEQUENCE_LIST_H

class Sequence_List
{
    private:
       int *array;                        //可以當做順序表的標識符 
       int length;                        //順序表實際長度
       int Max_len;                       //順序表規模 

    public:
       Sequence_List(int size);        //構造函數,確定順序表規模 
       Sequence_List(int size,int t);  //重構構造函數 
       ~Sequence_List(){}              //析構函數 
       int search_x(int x);           //按值查詢
       bool Find_k(int k,int *x);     //按序號查找 
       bool insert_k(int k,int x);    //在第k個位置插入x 
       void insert_x(int x);          //在順序表尾插入x 
       void delete_k(int k);          //刪除第k個元素 
       int  Squlen(){return length;}  //返回當前順序表長度 
       void show();                   //顯示順序表所有元素 
};

#endif
//Sequence_List.cpp文件
//順序表類的實現文件

#include <iostream>
#include "Sequence_List.h"
using namespace std;

//留出數組第一個元素array[0],從array[1]開始到array[length]
Sequence_List::Sequence_List(int size)
{
    Max_len = size+1;
    length  = 0;  
    array = new int[size+1];
} 

//賦值初始化,對前t個元素進行賦值,t<=size
Sequence_List::Sequence_List(int size,int t) 
{
    Max_len = size+1;
    array = new int[size+1];    
    for(int i=1;i<=t;i++)
    {
        cout<<"input the "<<i<<"th data:";
        cin>>array[i];
    }
    length = t;
}

//按值查找x,如果成功返回序號,失敗返回0,設置監視哨 
int Sequence_List::search_x(int x)
{
    array[0]=x;
    int i=length;
    while(array[i--]!=x) ;
    return i+1;
} 

//按序號查找第k個元素,查找成功將該元素值傳給x,返回true,查找失敗返回false 
bool Sequence_List::Find_k(int k,int *x)
{
    if(k<1||k>length) return false;
    *x = array[k];
    return true; 
} 

//在第k個位置插入值爲x的元素 
bool Sequence_List::insert_k(int k,int x)
{
    if(k<1||k>length||length==Max_len) return false;
    int i; 
    for(i=length;i>=k;i--)
       array[i+1]=array[i];
    array[i]=x;
    return true;
} 

//直接在順序表最後插入一個元素
void Sequence_List::insert_x(int x)
{
    if(length==Max_len) {cout<<"error"<<endl;return ;}
    array[++length]=x;
} 

//刪除第k個元素
void Sequence_List::delete_k(int k)
{
    if(k<1||k>length) {  cout<<"error"<<endl;return ;}
    for(int i=k;i<length;i++)
       array[i]=array[i+1];
    length--;
}

//打印全表
void Sequence_List::show()
{
    for(int i=1;i<=length;i++)
       cout<<array[i]<<' ';
} 

還是寫了一個小測試主程序,同文件夾下包含了Sequence_List.cpp文件就可以使用這個數據結構了,雖然只是練手之用。

//test.cpp

#include <iostream>
#include "Sequence_List.cpp"
using namespace std; 

int main()
{
    //構造函數 
    Sequence_List *L = new Sequence_List(10,5);
    //按序號查找
    int t;
    if(L->Find_k(2,&t)) cout<<"the 2th data is:"<<t<<endl;
    //順序表尾插入x&&按值查找
    L->insert_x(25);
    cout<<"25 is the "<<L->search_x(25)<<"th"<<endl;
    //刪除第k個元素&&打印全表
    L->delete_k(3);
    L->show(); 
}

文本測試結果:
input the 1th data:1
input the 2th data:2
input the 3th data:3
input the 4th data:4
input the 5th data:5
the 2th data is:2
25 is the 6th
1 2 4 5 25

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章