已知一个顺序表A,请设计一个算法,将A分解为两个顺序表B,C,其中顺序表B中的值是A中小于0的元素,C中的值是A中大于0的元素。使用c++,使用顺序表,使用万能头文件
时间: 2024-10-10 20:02:08 浏览: 19
首先,我们需要创建一个`Node`结构体作为顺序表节点,然后设计一个`SequenceList`类表示顺序表。为了处理小于0和大于0的元素,我们可以遍历顺序表A,同时维护两个指针分别指向正数区和负数区。下面是具体的C++代码实现:
```cpp
#include <iostream>
// 定义节点结构
struct Node {
int data;
Node* next;
};
// 顺序表类
class SequenceList {
private:
Node* head;
public:
// 构造函数和析构函数
SequenceList() : head(nullptr) {}
~SequenceList();
// 添加元素到链表
void add(int value);
// 分割函数
void splitIntoPositiveNegative(SequenceList& positive, SequenceList& negative);
};
// 序列表的添加元素方法
void SequenceList::add(int value) {
Node* newNode = new Node{value, nullptr};
if (!head) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr && current->next->data > 0) {
current = current->next;
}
if (current->next == nullptr || current->next->data <= 0) {
current->next = newNode;
} else {
newNode->next = current->next;
}
}
}
// 分解顺序表
void SequenceList::splitIntoPositiveNegative(SequenceList& positive, SequenceList& negative) {
Node* positiveHead = nullptr;
Node* negativeHead = nullptr;
Node* current = head;
while (current != nullptr) {
if (current->data < 0) {
if (!negativeHead) {
negativeHead = current;
} else {
negative->tail->next = current;
negative->tail = current;
}
} else {
if (!positiveHead) {
positiveHead = current;
} else {
positive->tail->next = current;
positive->tail = current;
}
}
current = current->next;
}
positive.head = positiveHead;
negative.head = negativeHead;
}
// 序列表的析构函数释放内存
SequenceList::~SequenceList() {
Node* temp = head;
while (temp != nullptr) {
Node* nextTemp = temp->next;
delete temp;
temp = nextTemp;
}
}
int main() {
SequenceList A;
// ... (添加一些元素给A)
SequenceList B, C;
A.splitIntoPositiveNegative(B, C);
// ... (打印B和C中的元素)
return 0;
}
```
阅读全文