使用c语言,用链表储存三元组,并在链表末尾插入多个三元组
时间: 2023-07-12 08:21:42 浏览: 51
好的,以下是一个使用 C 语言实现的链表储存三元组,并在链表末尾插入多个三元组的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Triple {
int a;
int b;
int c;
} Triple;
typedef struct Node {
Triple data;
struct Node* next;
} Node;
void insert_triples_at_end(Node* head, Triple* triples, int num_triples) {
Node* curr = head;
// 找到末尾节点
while (curr->next != NULL) {
curr = curr->next;
}
// 将多个三元组插入到末尾节点后面
for (int i = 0; i < num_triples; i++) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = triples[i];
new_node->next = NULL;
curr->next = new_node;
curr = new_node;
}
}
int main() {
// 创建头节点
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
// 创建三个三元组
Triple t1 = {1, 2, 3};
Triple t2 = {4, 5, 6};
Triple t3 = {7, 8, 9};
Triple triples[] = {t1, t2, t3};
// 在链表末尾插入三元组
insert_triples_at_end(head, triples, 3);
// 遍历链表,输出三元组
Node* curr = head->next;
while (curr != NULL) {
printf("(%d, %d, %d)\n", curr->data.a, curr->data.b, curr->data.c);
curr = curr->next;
}
// 释放节点内存
curr = head;
while (curr != NULL) {
Node* temp = curr;
curr = curr->next;
free(temp);
}
return 0;
}
```
这个程序创建了一个头节点,并且定义了一个 `Triple` 结构体用来存储三元组的三个元素。然后在 `insert_triples_at_end` 函数中,遍历链表找到末尾节点,并将多个三元组插入到末尾节点后面。最后在 `main` 函数中,创建了三个三元组并调用 `insert_triples_at_end` 函数,在链表末尾插入三元组。最后遍历链表,输出三元组,并释放节点内存。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)