1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 class Vector { 6 public: 7 Vector(int input_size) { 8 size = input_size; 9 length = 0; 10 data = new int[size]; 11 } 12 13 ~Vector() { 14 delete[] data; 15 } 16 17 void insert(const int& value, int loc) { 18 if (loc < 0 || loc > length) { 19 return; 20 } 21 for (int i = length; i > loc ; i--) { 22 data[i] = data[i - 1]; 23 } 24 data[loc] = value; 25 length ++; 26 } 27 28 int at(const int& loc) { 29 return data[loc]; 30 } 31 32 int getLen() { 33 return length; 34 } 35 36 void output() { 37 cout << length << endl; 38 for (int i = 0; i < length; ++i) { 39 if (i == 0) cout << data[i]; 40 else cout << " " << data[i]; 41 } 42 cout << endl; 43 } 44 private: 45 int size, length; 46 int * data; 47 }; 48 49 50 int main() { 51 int a, b; 52 cin >> a; 53 Vector A(a); 54 for (int i = 0; i < a; ++i) { 55 int num; 56 cin >> num; 57 A.insert(num, i); 58 } 59 cin >> b; 60 Vector B(b); 61 for (int i = 0; i < b; ++i) { 62 int num; 63 cin >> num; 64 B.insert(num, i); 65 } 66 67 int i = 0, j = 0, k = 0; 68 69 Vector C(a); 70 while (i < A.getLen() && j < B.getLen()) { 71 if (A.at(i) == B.at(j)) { 72 C.insert(A.at(i), k ++); 73 i ++; 74 j ++; 75 } else if (A.at(i) > B.at(j)) { 76 j ++; 77 } else if (A.at(i) < B.at(j)) { 78 i ++; 79 } 80 } 81 C.output(); 82 83 return 0; 84 }
其实可以用很简洁的代码实现,只是因为自己写了个顺序表类所以代码很长,重点看main函数里的while循环就可以了...
时间: 2024-09-30 10:16:37