資料結構中的兩個順序表的合併
阿新 • • 發佈:2018-11-17
#include <iostream> #include<stdlib.h> using namespace std; #define MAXSIZE 100 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int ElemType; typedef struct { ElemType *elem; //指向資料元素的基地址 int length; //線性表的當前長度 }SqList; Status InitList_Sq(SqList *L) { //構造一個空的順序表L L-> elem=new ElemType[MAXSIZE]; if(! L-> elem) exit(OVERFLOW); L-> length=0; return OK; } Status CreateList_Sq(SqList &L,int n) { int i; if(!L.elem||n<0||n>MAXSIZE) return ERROR; for(i=1;i<=n;i++) cin>>L.elem[i-1]; L.length=n; return OK; } void TraverseList_Sq(SqList &L) { int i; cout<<L.elem[0]; for(i=1;i<=L.length-1;i++) { cout<<','<<L.elem[i]; } cout<<endl; } void ListInsert_Sq(SqList &L,int e) { L.elem[L.length] = e; L.length++; } int ListLength(SqList L) { return L.length; } void GetElem(SqList L, int i, int &e) { e = L.elem[i - 1]; } bool LocateElem(SqList L, int e) { int i; for (i = 0; i < L.length; i++) if (e == L.elem[i]) return true; return false; } void MergeList_Sq(SqList L,SqList p,SqList q) { int i=1,j=1,e,f; //下面是主要的演算法 while((i<=ListLength(L))&&(j<=ListLength(p))){ GetElem(L,i,e);GetElem(p,j,f); if(e<=f){ ListInsert_Sq(q,e);i++; }else { ListInsert_Sq(q,f);j++; } } while(i<=L.length){ GetElem(L,i,e); ListInsert_Sq(q,e); i++; } while(j<=p.length){ GetElem(p,j,f); ListInsert_Sq(q,f); j++; } TraverseList_Sq(q); } int main() { SqList LA, LB,LC; int m,n; InitList_Sq(&LA); InitList_Sq(&LB); InitList_Sq(&LC); //提示:請輸入有序表LA的元素個數 cin>>n; //提示:輸入有序表LB中的元素 CreateList_Sq(LA, n); TraverseList_Sq(LA); //提示:請輸入有序表LB的元素個數 cin>>m; //提示:輸入有序表LB中的元素 CreateList_Sq(LB, m); TraverseList_Sq(LB); //在此處呼叫有序表合併函式MergeList_Sq MergeList_Sq(LA,LB,LC); //提示:LA和LB合併後的集合LC為: //TraverseList_Sq(LC); return 0; }
/*
思路:::如果LA和LB是兩個已經按照遞減排列的順序表,可以進行用兩個數分別迴圈到兩個表的最後,在這期間,c=a(a<=b);
c=b(a>b);如果LA先到達末尾,則將剩餘的LB表中的元素直接插入到LC即可,如果LB表先到大末尾,同理。
*/