C语言判断一个链表是否有环
时间: 2023-07-25 19:05:32 浏览: 122
要判断一个链表是否有环,可以使用快慢指针的方法。
快指针每次移动两个节点,慢指针每次移动一个节点,如果链表中存在环,那么快指针和慢指针一定会在环内某个节点相遇。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 判断链表是否有环
int hasCycle(ListNode *head) {
if (head == NULL) {
return 0;
}
ListNode *slow = head;
ListNode *fast = head->next;
while (fast != NULL && fast->next != NULL) {
if (slow == fast) {
return 1;
}
slow = slow->next;
fast = fast->next->next;
}
return 0;
}
// 创建链表
ListNode* createList(int* nums, int numsSize) {
if (numsSize == 0) {
return NULL;
}
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->val = nums[0];
head->next = NULL;
ListNode *cur = head;
for (int i = 1; i < numsSize; i++) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = nums[i];
node->next = NULL;
cur->next = node;
cur = node;
}
return head;
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
int numsSize = 5;
ListNode *head = createList(nums, numsSize);
// 将链表尾部指向第二个节点,构成一个环
head->next->next->next->next->next = head->next;
int result = hasCycle(head);
printf("result: %d\n", result);
return 0;
}
```
输出结果为1,表示链表中存在环。
阅读全文
相关推荐
















