C 语言实现:创建无环与循环链表并计算环的长度
以下是使用 C 语言创建无环链表和循环链表,并计算循环链表中环的长度的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 链表节点结构体 typedef struct Node { int data; struct Node *next; } Node; // 创建无环链表 Node* createNonCyclicList() { Node *head = NULL, *tail = NULL, *newNode; int num, choice; do { printf("输入节点值: "); scanf("%d", &num); newNode = (Node*)malloc(sizeof(Node)); newNode->data = num; newNode->next = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } printf("是否继续添加节点(1 继续,0 停止): "); scanf("%d", &choice); } while (choice); return head; } // 创建循环链表 Node* createCyclicList() { Node *head = NULL, *tail = NULL, *newNode; int num, choice; do { printf("输入节点值: "); scanf("%d", &num); newNode = (Node*)malloc(sizeof(Node)); newNode->data = num; newNode->next = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } printf("是否继续添加节点(1 继续,0 停止): "); scanf("%d", &choice); } while (choice); // 使链表成为循环链表 tail->next = head; return head; } // 计算循环链表中环的长度 int calculateCycleLength(Node *head) { Node *slow = head, *fast = head; int length = 0; // 找到相遇点 while (fast!= NULL && fast->next!= NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) { break; } } if (slow!= fast) { // 没有环 return 0; } // 计算环的长度 do { slow = slow->next; length++; } while (slow!= fast); return length; } // 打印链表 void printList(Node *head) { Node *current = head; while (current!= NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } int main() { Node *nonCyclicHead = createNonCyclicList(); printf("无环链表: "); printList(nonCyclicHead); Node *cyclicHead = createCyclicList(); printf("循环链表: "); printList(cyclicHead); int cycleLength = calculateCycleLength(cyclicHead); if (cycleLength > 0) { printf("循环链表中环的长度: %d\n", cycleLength); } else { printf("该链表不是循环链表或没有环\n"); } return 0; } ``` 这段代码首先分别实现了创建无环链表和循环链表的函数,然后通过快慢指针的方法计算循环链表中环的长度。 ######[AI写代码神器 | 843点数解答 | 2024-10-09 16:47:07]
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)375
- Java 创建 HTTP POST 请求实现文件上传:代码示例与注意要点 (字节豆包 | 300点数解答 | 2024-12-06 16:07:20)353
- 用 JS 中 for 循环实现 1 到 100 相加并输出结果到页面的完整代码 ( | 240点数解答 | 2024-05-20 22:11:29)495
- 用 JS 的 while 循环实现 1 到 100 相加并输出到页面的代码揭秘( | 47点数解答 | 2024-05-20 22:16:48)381
- C#工程师必知:数组、链表、哈希、队列、栈数据结构优缺点大揭秘! (百度文心 | 561点数解答 | 2023-11-09 17:56:30)276
- Java 实现仿 Windows 资源管理器:文件管理器功能全解析与代码示例(字节豆包 | 623点数解答 | 2025-01-01 14:59:04)268
- C++实现读取数字并输出最小值的代码及解释(字节豆包 | 113点数解答 | 2026-03-20 19:32:56)26
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)345
- C++ 代码实现自定义运算 x@y = x² + y² - xy 及 x@(x+y) 计算(DeepSeek | 215点数解答 | 2025-12-13 15:08:14)93
- C++ 实现根据输入正整数奇偶性计算偶数和或约数和(字节豆包 | 838点数解答 | 2026-02-28 20:23:59)52
- Python知识大挑战:10 道题揭秘编程关键要点与答案(字节豆包 | 296点数解答 | 2024-10-20 19:31:00)241
- 函数详解:shu_ju_jie_gou实现数据结构处理与统计 (字节豆包 | 279点数解答 | 2024-10-31 14:31:13)169