// 自定义ArrayList类,实现线性列表(类似数组)结构的数据元素操作。操作方法: // 1. add(int) 添加int整型的数据元素 // 2. remove(int) 删除数据元素 // 3. int get(int index) 获取指定位置的元素 // 4. void print() 打印列表中所有元素 // 5. int size() 返回列表的当前大小 // 6. void sort(bool reversed = false) 元素排序,reversed为true时,表示从大小到小,反之,表示从小到到。 #include using namespace std; class ArrayList { private: int *elements; // 存储元素的数组 int capacity; // 数组的容量 int count; // 当前元素的数量 public: ArrayList() : capacity(10), elements(new int[capacity]), count(0) {} ~ArrayList() { delete[] elements; } public: void add(int value); void remove(int index); int get(int index); void print(); int size(); void sort(bool reversed = false); }; void ArrayList::add(int value) { if (count == capacity) { // 如果数组已满,扩容为原来的两倍 int newCapacity = capacity * 2; int *newElements = new int[newCapacity]; for (int i = 0; i < count; i++) { newElements[i] == elements[i]; } delete[] elements; elements = newElements; capacity = newCapacity; } elements[count] = value; count++; } void ArrayList::remove(int index) { if (index >= 0 && index < count) { for (int i = index; i < count - 1; i++) { // index 后面的元素全部前移一位 elements[i] = elements[i + 1]; } count--; } } int ArrayList::get(int index) { if (index >= 0 && index < count) return elements[index]; return -1; // 返回无效值,表示未找到内容 } void ArrayList::print() { for (int i = 0; i < count; i++) cout << elements[i] << " "; cout << endl; } int ArrayList::size() { return count; } void ArrayList::sort(bool reversed) { for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - i - 1; j++) { if (reversed) // 等价于 reversed == true { if (elements[j] < elements[j + 1]) { int tmp = elements[j]; elements[j] = elements[j + 1]; elements[j + 1] = tmp; } } else { if (elements[j] > elements[j + 1]) { int tmp = elements[j]; elements[j] = elements[j + 1]; elements[j + 1] = tmp; } } } } } int main() { ArrayList list; list.add(5); list.add(8); list.add(7); list.add(2); list.add(1); cout << "原始列表: "; list.print(); cout << endl; cout << "列表大小为: " << list.size() << endl; cout << "删除第二位的元素后显示为: "; list.remove(2); list.print(); cout << endl; cout << "此时第二位的元素为: " << list.get(2) << endl; cout << "从大到小排序后列表为: "; list.sort(true); list.print(); cout << endl; cout << "从小到大排序后列表为: "; list.sort(); list.print(); cout << endl; return 0; }