1. 程式人生 > >資料結構(C++):順序表的實現

資料結構(C++):順序表的實現

包含取值、查詢、插入、刪除等功能: 

#include <iostream>
using namespace std;
typedef int ElemType;

//定義
#define MAXSIZE 100
typedef struct
{ElemType *elem;int length;}SqList;

//建立
bool CreateList(SqList &L)
{
    int i;
    L.elem=new ElemType[MAXSIZE];
    if(!L.elem) return false;
    cout<<"請輸入線性表的長度,不能大於"<<MAXSIZE<<':'<<endl; cin>>L.length;
    cout<<"請依次輸入表中元素:"<<endl;
    for(i=0;i<L.length;i++)
        cin>>L.elem[i];
    cout<<"建立完成!"<<endl;
}


//取值
bool GetElem(SqList L,int i ,ElemType &e)
{
    if (i<1||i>L.length) cout<<"位置不合理"<<endl;
    e=L.elem[i-1];
    return true;
}
//查詢
bool LocateElem(SqList L,ElemType e)
{
    //在順序表中查詢值為e的元素,返回其序號
    for(int i=0;i<L.length;i++)
        {if(L.elem[i]==e) cout<<e<<"是"<<i+1<<"號元素"<<endl;
         else cout<<"查詢失敗,無此元素!"<<endl;break;
        } //查詢結果
    return true;   //查詢失敗,返回0
}

//插入
bool ListInsert(SqList &L,int i,ElemType e)
{
    //在順序表L中第i個位置插入新的元素e,i值的合法範圍是1<=i<=L.length+1
     if(i<1||i>L.length+1){ cout<<"插入位置有誤! " <<endl; return  false; }  //i值不合法
     if(L.length==MAXSIZE){ cout<<"當前順序表已滿,無儲存空間! " <<endl;return  false; } //當前儲存空間已滿
     for(int j=L.length-1;j>=i-1;j--)
        L.elem[j+1]=L.elem[j];
     L.elem[i-1]=e;
     ++L.length;
     return true;
}

//刪除
bool ListDelete(SqList &L,int i )
{
    //在順序表L中刪除第i個元素,i值的合法範圍是1<=i<=L.length
    if(i<1||i>L.length){ cout<<"刪除序號錯! " ; return  false; }
    for(int j=i;j<=L.length-1;j++)
        L.elem[j-1]=L.elem[j];
    --L.length;
    return true;
}

//輸出表
void print(SqList L)
{ int i;
  cout<<'(';
  for(i=0;i<L.length;i++)
     {if (i==L.length-1)cout<<L.elem[i];
      else cout<<L.elem[i]<<',';}
  cout<<')'<<endl;
}

int main()
{ SqList L; int i,x; ElemType e;
  cout<<"----------------歡迎使用線性表!----------------"<<endl;
  cout<<"              建立[1]    ";
  cout<<"查詢[5]"<<endl;
  cout<<"              輸出[2]    ";
  cout<<"取值[6]"<<endl;
  cout<<"              插入[3]    -------"<<endl;
  cout<<"              刪除[4]    ";
  cout<<"退出[0]"<<endl;
  cout<<"------------------------------------------------"<<endl;
  cout<<"請輸入你的選擇:"<<endl;

  cin>>x;
  while(x)
    {  switch(x)
       { case 1:CreateList(L); break;
         case 2:cout<<"當前線性表為:";print(L);break;
         case 3:cout<<"請輸入插入位置:"<<endl;   cin>>i;
                cout<<"請輸入待插入元素:"<<endl; cin>>e;
                ListInsert(L,i,e) ;
                cout<<"插入成功!"<<endl;
                break;
         case 4:cout<<"請輸入刪除位置:"<<endl; cin>>i;
                ListDelete(L,i);
                cout<<"刪除成功!"<<endl;
				break;
         case 5:cout<<"請輸入要查詢的元素:"<<endl;cin>>e;
                LocateElem(L,e);break;
         case 6:cout<<"請輸入要取值的位置:"<<endl;cin>>i;
                GetElem(L,i,e);
                cout<<i<<"號位置的元素為:"<<e<<endl;
         case 0:break;
         default:cout<<"你的選擇有錯,請重新選擇!"<<endl ;
	   }
	   cout<<"請輸入你的選擇:"<<endl; cin>>x;
    }
  return 0;
}