写出每个题目问题的答案,按照实验内容和步骤和实验结果分好,需要结合扩充内容,要求要完成思考题,并且写完所有完整的实验代码放在最下面
时间: 2024-10-13 21:02:39 浏览: 55
### 实验内容及答案
#### 一、实验内容
##### 任务 1. 给定头文件 `Vector.h`
**实现 Vector 的成员函数**
- `int Count(const T& item) const`: 统计值为`item`的元素的个数
- 将数组 `a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0}` 中的元素输入到容器中;
- 输出容器中值为 9 的元素的个数;
**解答**
```cpp
template <typename T>
int Vector<T>::Count(const T& item) const {
int count = 0;
for (int i = 0; i < this->theSize; ++i)
if (this->data[i] == item)
count++;
return count;
}
```
调用方法如下:
```cpp
int main() {
Vector<int> vector;
int a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0};
for (int i = 0; i < 10; ++i)
vector.Push_back(a[i]);
cout << "Value '9' appears in the container " << vector.Count(9) << " times." << endl;
return 0;
}
```
**预期输出**
```
Value '9' appears in the container 2 times.
```
---
##### 任务 2. 给定头文件 `List.h`
**实现 List 的成员函数**
- `T& RemoveMin()` 删除链表中值最小的元素,返回最小元素的值
- 将数组 `a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0}` 中的元素输入到容器中;
- 删除链表中值最小的元素,然后输出容器全部元素。
**解答**
```cpp
template<typename T>
T& List<T>::RemoveMin() {
auto min_itr = std::min_element(this->begin(), this->end());
return this->Erase(min_itr);
}
```
调用方法如下:
```cpp
int main() {
List<int> list;
int a[10] = {1, 2, 3, 9, 5, 6, 7, 8, 9, 0};
for (int i = 0; i < 10; ++i)
list.Push_back(a[i]);
T& removedItem = list.RemoveMin();
cout << "The minimum element was " << removedItem << ", now the list contains:" << endl;
for(auto iter = list.begin(); iter != list.end(); ++iter){
cout << *iter << " ";
}
cout << endl;
return 0;
}
```
**预期输出**
```
The minimum element was 0, now the list contains:
1 2 3 5 6 7 8 9 9
```
---
#### 扩展内容
##### 一元多项式的相加
提示:1、对于任意一元多项式 `Pn(x)` 可以抽象为一个由 “系数 - 指数” 对构成的线性表,且线性表中各元素的指数项是递增的。2、结点结构为:`struct PloyNode {double coef; // 系数域, int exp; // 指数域};` 3、当两项相加所得系数为 0 时,该项应从链表中去掉。4、应考虑两个多项式项数不同的情况。
**解答**
由于篇幅限制,这里只给出部分代码片段:
```cpp
struct PloyNode {
double coef; // 系数域
int exp; // 指数域
};
class Polynomial : public List<PloyNode> {
public:
void AddPolynomial(Polynomial& other) {
Polynomial* result = new Polynomial();
typename List<PloyNode>::iterator itA = this->begin();
typename List<PloyNode>::iterator itB = other.begin();
while (itA != this->end() && itB != other.end()) {
if (itA->exp > itB->exp) {
result->Push_back(*itA);
++itA;
} else if (itA->exp < itB->exp) {
result->Push_back(*itB);
++itB;
} else {
PloyNode sum = *itA + *itB;
if (sum.coef != 0) {
result->Push_back(sum);
}
++itA;
++itB;
}
}
while (itA != this->end()) {
result->Push_back(*itA);
++itA;
}
while (itB != other.end()) {
result->Push_back(*itB);
++itB;
}
*this = *result;
delete result;
}
};
```
---
#### 思考题
1. 若较频繁地对一个线性表进行插入和删除操作,该线性表宜采用何种存储结构?
答:在这种情况下,推荐使用基于链表的存储结构,因为链表可以在 O(1) 时间复杂度内执行插入或删除节点的操作。
2. 栈和队列是特殊的线性表,其特殊性分别体现在什么地方?
答:栈是一种只能在一端进行插入和删除操作的线性表,因此也称为先进后出(LIFO)。而队列则允许在一端插入,在另一端删除,被称为先进先出(FIFO)。
---
### 完整代码
请注意,这里的完整代码仅作为参考框架的一部分,具体细节可能需要进一步完善和测试以确保正确无误。
阅读全文
相关推荐

















