用链表储存三元组
时间: 2023-07-10 16:24:30 浏览: 52
三元组是由三个元素组成的有序组合,可以用链表来储存。
链表节点可以定义如下:
```C++
struct Node {
int val1; // 第一个元素
int val2; // 第二个元素
int val3; // 第三个元素
Node* next; // 指向下一个节点的指针
};
```
然后可以定义一个链表类,包含插入、删除、查找等操作:
```C++
class LinkedList {
public:
LinkedList() {
head = new Node;
head->next = nullptr;
}
// 在链表末尾插入一个三元组
void insert(int v1, int v2, int v3) {
Node* cur = head;
while (cur->next != nullptr) {
cur = cur->next;
}
Node* node = new Node;
node->val1 = v1;
node->val2 = v2;
node->val3 = v3;
node->next = nullptr;
cur->next = node;
}
// 删除链表中指定的三元组
void remove(int v1, int v2, int v3) {
Node* cur = head;
while (cur->next != nullptr) {
if (cur->next->val1 == v1 && cur->next->val2 == v2 && cur->next->val3 == v3) {
Node* temp = cur->next;
cur->next = cur->next->next;
delete temp;
return;
}
cur = cur->next;
}
}
// 查找链表中指定的三元组
bool find(int v1, int v2, int v3) {
Node* cur = head->next;
while (cur != nullptr) {
if (cur->val1 == v1 && cur->val2 == v2 && cur->val3 == v3) {
return true;
}
cur = cur->next;
}
return false;
}
private:
Node* head;
};
```
使用示例:
```C++
int main() {
LinkedList list;
list.insert(1, 2, 3);
list.insert(4, 5, 6);
list.insert(7, 8, 9);
list.remove(4, 5, 6);
cout << list.find(7, 8, 9) << endl; // 输出 1
cout << list.find(4, 5, 6) << endl; // 输出 0
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)