將兩個順序表合併爲一個新的順序表

問題描述:將兩個有序順序表合併爲一個新的有序順序表,並有函數返回結果順序表。要求時間複雜度O(n)算法

算法設計思想:首先,按順序取兩個順序表表頭較小的結點存入新的線性表中直到某一個表遍歷完;而後將還有剩餘元素的表的剩下結點加到新的順序表後。函數

代碼及結果:設計

#include<stdio.h>
#include "線性表的順序表示和實現.cpp"

bool Merge(SqList &A,SqList &B,SqList &L){
	//將有序順序表A和B合併成一個新的有序順序表L
	if(A.length + B.length > MaxSize) //兩個表的結點總個數大於順序表的最大長度
		return false;
	int i = 0,j = 0,k = 0;
	while(i < A.length && j < B.length){ //循環,將表頭較小的結點存入線性表中 
		if(A.data[i] < B.data[j])
			ListInsert_Sq(L,++k,A.data[i++]);
		else
			ListInsert_Sq(L,++k,B.data[j++]);
	} 
	while(i < A.length) //將還有剩餘元素的表中的剩下結點加到L後 
		ListInsert_Sq(L,++k,A.data[i++]);
	while(j < B.length)
		ListInsert_Sq(L,++k,B.data[j++]); 
	L.length = k;
	
	return true;
}

int main(){
	//Test
	SqList A,B,L;
	int e;
	InitList_Sq(A);
	InitList_Sq(B);
	InitList_Sq(L);
	
	printf("依次輸入要往線性表A中輸入的元素:"); 
	int i = 0;
	while(scanf("%d",&e)!=EOF){
		ListInsert_Sq(A,++i,e);
	}		
	printf("順序表A中現有的數據爲:");
	PrintList(A);
	
	printf("依次輸入要往線性表B中輸入的元素:"); 
	i = 0;
	while(scanf("%d",&e)!=EOF){
		ListInsert_Sq(B,++i,e);
	}		
	printf("順序表B中現有的數據爲:");
	PrintList(B);
	
	printf("合併以後的順序表爲:");
	Merge(A,B,L);
	PrintList(L);
	
	return 0;
	
}

相關文章
相關標籤/搜索