用c语言写一个循环链表解决两数之和问题的代码
时间: 2024-04-11 16:28:57 浏览: 16
下面是使用循环链表解决两数之和问题的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义循环链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建循环链表
Node* createCircularLinkedList(int n) {
Node* head = NULL;
Node* current = NULL;
for (int i = 0; i < n; i++) {
// 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败!");
exit(1);
}
// 输入节点值
printf("请输入第 %d 个节点的值:", i + 1);
scanf("%d", &(newNode->data));
// 将新节点加入链表
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
// 将最后一个节点的next指向头节点,形成循环链表
current->next = head;
return head;
}
// 计算两数之和
int sumOfTwoNumbers(Node* head, int num1, int num2) {
Node* temp = head;
int sum = 0;
// 遍历链表,查找num1和num2所在的节点,并计算两数之和
do {
if (temp->data == num1 || temp->data == num2) {
sum += temp->data;
}
temp = temp->next;
} while (temp != head);
return sum;
}
int main() {
int n; // 链表节点个数
int num1, num2; // 需要计算的两个数
printf("请输入链表节点个数:");
scanf("%d", &n);
Node* head = createCircularLinkedList(n);
printf("请输入需要计算的两个数:");
scanf("%d %d", &num1, &num2);
int sum = sumOfTwoNumbers(head, num1, num2);
printf("两数之和为:%d\n", sum);
return 0;
}
```
这段代码中,我们首先定义了循环链表的节点结构体 `Node`,然后通过 `createCircularLinkedList` 函数创建了一个循环链表,并将输入的节点值存储在链表中。接下来,使用 `sumOfTwoNumbers` 函数遍历链表,查找给定的两个数并计算它们的和。最后,将计算结果输出到控制台。
相关推荐
![](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)