qfedu-cpp-level/day4/homework/h6_2.cpp

148 lines
3.3 KiB
C++
Raw Permalink Normal View History

2023-07-28 09:20:37 +08:00
// 自定义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时表示从大小到小反之表示从小到到。
2023-07-27 21:04:06 +08:00
#include <iostream>
using namespace std;
2023-07-27 21:04:06 +08:00
class ArrayList
{
private:
2023-07-28 09:20:37 +08:00
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;
}