输入第一个顺序表 1 2 3 4 5 , 输入第二个顺序表 7, 8, 9, 依次存放在一维数组中,在数组中将两个顺序表的位置互换
时间: 2024-03-03 08:53:29 浏览: 72
5 第5章 数组和广义表1
假设第一个顺序表存放在数组a中,第二个顺序表存放在数组b中,长度分别为n和m,则交换两个顺序表的位置可以按照以下步骤进行:
1. 定义一个临时数组temp,长度为n+m:
```
int temp[n+m];
```
2. 将数组a和数组b按顺序拷贝到temp数组中:
```
for (int i = 0; i < n; i++) {
temp[i] = a[i];
}
for (int i = n; i < n+m; i++) {
temp[i] = b[i-n];
}
```
3. 将temp数组中前m个元素和后n个元素交换位置:
```
for (int i = 0; i < m; i++) {
int t = temp[i];
temp[i] = temp[n+i];
temp[n+i] = t;
}
```
4. 将temp数组中的元素依次拷贝回数组a和数组b中:
```
for (int i = 0; i < n; i++) {
a[i] = temp[i+m];
}
for (int i = 0; i < m; i++) {
b[i] = temp[i];
}
```
完整代码如下:
```
#include <iostream>
using namespace std;
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {7, 8, 9};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
int temp[n+m];
for (int i = 0; i < n; i++) {
temp[i] = a[i];
}
for (int i = n; i < n+m; i++) {
temp[i] = b[i-n];
}
for (int i = 0; i < m; i++) {
int t = temp[i];
temp[i] = temp[n+i];
temp[n+i] = t;
}
for (int i = 0; i < n; i++) {
a[i] = temp[i+m];
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < m; i++) {
b[i] = temp[i];
cout << b[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
7 8 9 4 5
1 2 3
```
阅读全文