顺序表非递减顺序合并
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define MAXSIZE 100 4 /** 5 * 实验一 (1) 6 * @author Unchangedman 7 */ 8 typedef int ElemType; 9 10 typedef struct 11 { 12 ElemType data[MAXSIZE]; 13 int length; 14 }SqList; 15 16 void InitList(SqList &sq) 17 { 18 sq.length = 0; 19 } 20 21 int GetLength(SqList sq) 22 { 23 return sq.length; 24 } 25 26 int GetElem(SqList sq,int i,ElemType &e) /*求线性表中第i个元素*/ 27 { 28 if (i < 1 || i > sq.length) /*无效的i值*/ 29 return 0; 30 else 31 { 32 e = sq.data[i-1]; 33 return 1; 34 } 35 } 36 37 int InsElem(SqList &sq,ElemType x,int i) /*插入元素*/ 38 { 39 if (i<1 || i>sq.length+1) /*无效的参数i*/ 40 return 0; 41 for (int j = sq.length; j >= i; j--) /*将位置为i的结点及之后的结点后移*/ 42 sq.data[j] = sq.data[j-1]; 43 sq.data[i-1] = x; /*在位置i处放入x*/ 44 sq.length++; /*线性表长度增1*/ 45 return 1; 46 } 47 48 void PrintList(SqList &sq) 49 { 50 for(int i = 1; i <= sq.length; i++) 51 { 52 cout << sq.data[i - 1] << endl; 53 } 54 cout << endl; 55 } 56 57 void commonToC(SqList A, SqList B, SqList &C) 58 { 59 int i = 1, j = 1; 60 int k = 0; 61 62 int lena = GetLength(A), lenb = GetLength(B); 63 ElemType a, b; 64 while((i <= lena) && (j <= lenb)) 65 { 66 GetElem(A,i,a); 67 GetElem(B,j,b); 68 69 if (a <= b) 70 { 71 InsElem(C,a,++k); 72 ++i; 73 } 74 else{ 75 InsElem(C,b,++k); 76 ++j; 77 } 78 } 79 while(i <= lena) 80 { 81 GetElem(A,i++,a); 82 InsElem(C,a,++k); 83 } 84 while(j <= lenb) 85 { 86 GetElem(B,j++,b); 87 InsElem(C,b,++k); 88 } 89 } 90 91 void commonAB(SqList &A, SqList B) 92 { 93 for(int i = 1; i <= GetLength(B); i++) 94 { 95 ElemType e; 96 GetElem(B,i,e); 97 int flag = 1; 98 for(int j = 1; j <= GetLength(A); j++) 99 { 100 ElemType a; 101 GetElem(A,j,a); 102 if(e <= a) 103 { 104 InsElem(A,e,j); 105 flag = 0; 106 break; 107 } 108 } 109 if(flag) 110 InsElem(A,e,GetLength(A) + 1); 111 } 112 } 113 int main() 114 { 115 SqList A,B,C; 116 InitList(A); /*初始化顺序表sq*/ 117 InitList(B); /*初始化顺序表sq*/ 118 InitList(C); /*初始化顺序表sq*/ 119 120 InsElem(A,3,1);//插入数据 121 InsElem(A,5,2); 122 InsElem(A,8,3); 123 InsElem(A,11,4); 124 cout << "A: " << endl; 125 PrintList(A);//打印表 A 126 127 InsElem(B,2,1);//插入数据 128 InsElem(B,6,2); 129 InsElem(B,8,3); 130 InsElem(B,9,4); 131 InsElem(B,11,5); 132 InsElem(B,15,6); 133 InsElem(B,20,7); 134 cout << "B: " << endl; 135 PrintList(B);//打印表 B 136 137 /* 138 A 和 B表合并到C表 139 元素值按非递减排列 140 */ 141 commonToC(A,B,C); 142 cout << "C :" << endl; 143 PrintList(C); 144 145 /* 146 A 和 B表合并到A表 147 元素值按非递减排列 148 */ 149 cout << "A: " << endl; 150 commonAB(A,B); 151 PrintList(A); 152 return 0; 153 }