写一个c++代码,查找顺序表中的最大值,并将最大值移动到顺序表的末尾,其它元素线性不变
时间: 2024-09-28 16:11:10 浏览: 57
当然可以。下面是一个简单的C++代码示例,它定义了一个`SequentialList`类,用于表示顺序表并包含查找最大值和移动最大值到末尾的功能:
```cpp
#include <iostream>
class SequentialList {
private:
int* elements; // 存储数据的指针
int size; // 序列表大小
int capacity; // 序列表容量
public:
SequentialList(int initial_capacity = 5) {
elements = new int[initial_capacity];
size = 0;
capacity = initial_capacity;
}
~SequentialList() {
delete[] elements;
}
void add(int value) {
if (size == capacity) {
resize(capacity * 2);
}
elements[size++] = value;
}
int findMax() const {
if (isEmpty()) {
throw std::runtime_error("Sequence list is empty");
}
return elements[size - 1]; // 返回最后一个元素作为最大值
}
void moveMaxToEnd() {
if (isEmpty()) {
throw std::runtime_error("Sequence list is empty");
}
int max_value = findMax();
for (int i = size - 1; i > 0; --i) { // 将最大值移到末尾
elements[i] = elements[i - 1];
}
elements[0] = max_value; // 将找到的最大值放到第一个位置
}
bool isEmpty() const {
return size == 0;
}
private:
void resize(int new_capacity) {
int* new_elements = new int[new_capacity];
for (int i = 0; i < size; ++i) {
new_elements[i] = elements[i];
}
delete[] elements;
elements = new_elements;
capacity = new_capacity;
}
};
int main() {
SequentialList list;
list.add(5);
list.add(10);
list.add(3);
list.add(8);
std::cout << "Original list: ";
for (int i : list.elements) {
std::cout << i << " ";
}
std::cout << "\n";
list.moveMaxToEnd();
std::cout << "List after moving max to end: ";
for (int i : list.elements) {
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}
```
在这个例子中,我们首先添加元素,然后找到最大值并将其移到末尾。注意这个程序假设顺序列表不会动态调整其内部结构以保持线性时间复杂度。
阅读全文