[資料結構][C++]使用線性表實現一個通訊錄
阿新 • • 發佈:2018-12-11
使用線性表實現一個通訊錄,通訊錄內容包含學號、姓名、電話三項資料。完成通訊錄資料的建立,紀錄插入和刪除功能。
#include <iostream.h> #include <conio.h> #include <iomanip.h> #include <string.h> //-------------------------------------------------------------------- struct ElemType // 資料元素的型別 { int numb; char name[20]; int tel; }; const int MAXSIZE=100; // 陣列的容量 class Sqlist { private: ElemType elem[MAXSIZE]; int length; public: Sqlist( void); ~Sqlist(){ }; void SetData(); void Insert( int i, ElemType e); ElemType Delet(int i); void PrintOut(); }; //------------------------------------------------------------- Sqlist::Sqlist( ) { length=0;} void Sqlist::SetData( ) //初步建立一個通訊錄 { cout<<"\n 輸入人數length="<<endl; cin>>length; for(int i=0;i<length;i++) { cout<<"\n 輸入學號:"; cin>>elem[i].numb; cout<<"\n 輸入姓名:"; cin>> elem[i].name; cout<<"\n 輸入電話號:="; cin>>elem[i].tel; } } void Sqlist::Insert( int i, ElemType e) //請完成此函式 { if(length==MAXSIZE) cout<<"FLOW!"<<endl; else if(i<1||i>length+1) cout<<"Insert ERROR!"<<endl; else for(int j=length;j>=i;j--) elem[j]=elem[j-1]; elem[i-1]=e; length++; cout<<"Insert success!"<<endl; } ElemType Sqlist::Delet(int i) { ElemType x; if(i<1||i>length) cout<<"RANGE ERROR!"<<endl; else { x=elem[i-1]; for(int j=i;j<length;j++) elem[j-1]=elem[j]; length--; cout<<"success"<<endl; } return x; } void Sqlist::PrintOut() //輸出 { cout<<"\n 通訊錄總人數:"<<length; cout<<"\n PrintOut Data:\n"; cout<<setw(16)<<"學號"<<setw(20)<<"姓名"<<setw(20)<<"電話號"<<endl; for(int k=0; k<length;k++) { cout<<setw(16)<<elem[k].numb<<setw(20)<<elem[k].name<<setw(20)<<elem[k].tel<<endl; } } //-------------------------------------------------- int main( ) { int i,k; ElemType e,x; Sqlist as; cout<<"\n 通訊錄演示"; do{ cout<<"\n\n"; cout<<"\n\n 1. 初步建立一個通訊錄(線性表) "; cout<<"\n\n 2. 插入一個數據元素 "; cout<<"\n\n 3. 刪除一個元素,返回其值"; cout<<"\n\n 4. 結束程式"; cout<<"\n******************************** "; cout<<"\n 請輸入你的選擇(1,2,3,4)"; cin>>k; switch(k) { case 1: { as.SetData(); as.PrintOut(); }break; case 2:{ cout<<"\n 插入的位置, i=?"; cin>>i; cout<<"\n 插入的資料 編號=?"; cin>>e.numb; cout<<"\n 插入的資料 姓名=?"; cin>>e.name; cout<<"\n 插入的資料 電話號=?"; cin>>e.tel; as.Insert(i,e); as.PrintOut(); }break; case 3:{ cout<<"\n 刪除第幾個元i=?"; cin>>i; x=as.Delet(i); cout<<"\n 被刪除的元素數值= "<<setw(10)<<x.numb<< setw(10)<<x.name<<setw(10)<<x.tel; as.PrintOut(); }break; default:break; } //switch }while(k>=1&&k<4); cout<<"\n 再見!"; cout<<"\n 按任意鍵,返回。"; _getch(); return 0; }