题目
给你一个链表的头节点head
,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪next
指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数pos
来表示链表尾连接到链表中的位置(索引从0
开始)。注意:pos
不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回true
。 否则,返回false
。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
代码
快慢指针
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
bool hasCycle(struct ListNode *head) {
if (head == NULL || head->next == NULL) {
return false;
} else {
struct ListNode* slow = head;
struct ListNode* fast = head->next;
while (fast != slow) {
if (fast->next == NULL || fast->next->next == NULL) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
}
int main() {
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 3;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 0;
head->next->next->next = head->next;
bool res = hasCycle(head);
printf("%d", res);
return 0;
}
分析
这个题目其实最容易想到的是哈希表,先放着。
快慢指针
很有意思的方法。围绕操场长跑,跑的快的能拉慢的好几圈,他们会相遇好几次。
由此,我们可以得出结论,只要有圈,就能相遇。慢的走一步,快的走两步。不同题目中的步距要根据目的来确定。