酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]