C++实现1、从键盘中输入 5 个无序的整数,插入到顺序表中,并保证插入 后顺序表中的数据要从小到大进行排序。2、顺序表的创建、查找、插入、删除和输出操作。
时间: 2024-10-11 18:13:22 浏览: 46
在C++中,你可以通过以下几个步骤实现这个功能:
1. **顺序表的创建**:
- 使用数组作为底层存储结构,因为顺序表(数组实现)的索引访问速度较快。
```cpp
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class SequentialList {
private:
Node* head;
int size;
public:
SequentialList() : head(nullptr), size(0) {}
};
```
2. **查找操作**:
- 查找特定元素,通过遍历链表直到找到或到达结尾。
```cpp
bool find(int target) {
Node* current = head;
while (current != nullptr && current->data != target) {
current = current->next;
}
return current != nullptr;
}
```
3. **插入操作(保持有序)**:
- 如果插入点在头部,直接插入并调整头指针。否则按顺序插入并在适当的位置进行比较。
```cpp
void insert(int value) {
Node* newNode = new Node{value, nullptr};
if (head == nullptr || value < head->data) {
newNode->next = head;
head = newNode;
} else {
Node* prev = nullptr;
for (Node* curr = head; curr != nullptr && value > curr->data; prev = curr, curr = curr->next) {}
newNode->next = curr;
if (prev != nullptr) {
prev->next = newNode;
} else {
head = newNode;
}
}
size++;
}
```
4. **删除操作**:
- 删除指定值的节点,需要更新前后节点的链接。
```cpp
void remove(int value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
size--;
return;
}
Node* prev = nullptr;
for (Node* curr = head; curr != nullptr; prev = curr, curr = curr->next) {
if (curr->data == value) {
prev->next = curr->next;
delete curr;
size--;
break;
}
}
}
5. **输出操作**:
- 遍历整个列表打印元素。
```cpp
void display() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
```
6. **主函数示例**:
```cpp
int main() {
SequentialList list;
// 输入5个整数
for (int i = 0; i < 5; ++i) {
int num;
cin >> num;
list.insert(num);
}
list.display(); // 输出排序后的列表
return 0;
}
```
阅读全文