資料結構實驗一:改
阿新 • • 發佈:2018-12-19
改進後的線性表
#include <iostream> #include<stdlib.h> using namespace std; typedef struct { int L[100]; int length; } SList; void InitList_Sq(SList*,int ); //初始化線性表 void Out_Sq(SList*); //輸出線性表 bool GetElem_Sq(SList*,int,int *); //根據位置返回元素 int LocatElem_Sq(SList*,int); //返回元素的位置 void ListInsert_Sq(SList*,int,int); //插入元素 void ListDelete_Sq(SList*,int); //刪除元素 void ListCombine_Sq(SList*,SList*); //合併兩個有序線性表 void ListDifferent_Sq(SList*,SList*); //兩個線性表的差集 int main () { SList L1,L2; int len1,place,val,loc,len2; int e,E; // len1是第一個表的長度 place存放要查詢元素的位置 e存放返回的元素 cout<<"輸入第一個表的個數:" ; cin>>len1; cout<<"輸入表的元素:"; InitList_Sq(&L1,len1); cout<<"表1為:"; Out_Sq(&L1); cout<<"輸入第二個表的個數:" ; cin>>len2; cout<<"輸入表的元素:"; InitList_Sq(&L2,len2); cout<<"表2為:"; Out_Sq(&L2); // cout<<"輸入要查詢的位置:"; // cin>>place; // cout<<"該位置的元素是:"; // GetElem_Sq(&L1,place, &e); // cout<<e; // cout<<"輸入要查詢位置的元素:"; // cin>>val; // LocatElem_Sq(&L1,val); // cout<<"輸入要插入的位置和元素:"; // cin>>loc>>E; // ListInsert_Sq(&L1,loc,E); // Out_Sq(&L1); // cout<<"輸入要刪除的元素:"; // cin>>E; // ListDelete_Sq(&L1,E); // Out_Sq(&L1); cout<<"L1UL2為:"; ListCombine_Sq(&L1,&L2); Out_Sq(&L1); cout<<"L1-L2為:" ; ListDifferent_Sq(&L1,&L2); Out_Sq(&L1); return 0; } void InitList_Sq(SList *L1,int len) { int i; for(i=0;i<len;i++) { cin>>L1->L[i]; } L1->length = len; } void Out_Sq(SList *L1) { int i= 0; for(i=0;i<L1->length;i++) cout<<L1->L[i]<<" "; cout<<endl; } bool GetElem_Sq(SList *L1,int place,int * e) { int i; if(place<0||place>L1->length) return false; else * e = L1->L[place-1]; return true; } int LocatElem_Sq(SList *L1,int val) { int i,j=-1; for(i = 0;i<L1->length;i++) { if(L1->L[i] == val) { j = i; break; } } return j; } void ListInsert_Sq(SList *L1,int loc,int E) { int i; if(loc<0||loc>L1->length+1) cout<<"插入位置錯誤!"; for(i = L1->length-1;i>=loc-1;i--) { L1->L[i+1]=L1->L[i]; } L1->L[loc-1] = E; L1->length++; } void ListDelete_Sq(SList *L1,int E) { int i; if(E<0||E>=L1->length) cout<<endl<<"位置錯誤"; for(i = E;i<L1->length;i++) L1->L[i] = L1->L[i+1]; L1->length--; } void ListCombine_Sq(SList *L1,SList *L2) { int i,j=0; for(i = 0;i<L2->length;i++) { while(L1->L[j]<=L2->L[i]&&j<L1->length) { j++; } ListInsert_Sq(L1,j+1,L2->L[i]); } } void ListDifferent_Sq(SList *L1,SList *L2) { int i,j; for(i = 0;i<L2->length;i++) { j = LocatElem_Sq(L1,L2->L[i]); if(j>=0) ListDelete_Sq(L1,j); } }