用c++在顺序表类SeqList和单链表类Chain中分别增加一个成员函数,其功能是删除表中所有等于item的数据元素。
时间: 2024-03-01 11:52:48 浏览: 37
在SeqList类中,可以增加如下成员函数:
```cpp
void removeItem(const T& item) {
int i = 0;
while (i < length) {
if (data[i] == item) {
for (int j = i; j < length - 1; ++j) {
data[j] = data[j + 1];
}
--length;
} else {
++i;
}
}
}
```
在Chain类中,可以增加如下成员函数:
```cpp
void removeItem(const T& item) {
ChainNode<T> *current = first, *prev = nullptr;
while (current != nullptr) {
if (current->element == item) {
if (prev == nullptr) {
first = current->next;
} else {
prev->next = current->next;
}
ChainNode<T> *toDelete = current;
current = current->next;
delete toDelete;
--length;
} else {
prev = current;
current = current->next;
}
}
}
```
以上代码都是基于模板类的,可以对不同类型的数据使用。这里假设T代表数据类型。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)