题目
给定一个链表,判断链表中是否有环。
要求:
你能否不使用额外空间解决此题?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
//在此处编辑代码
}
题解
思路: 用一对快慢指针同时遍历链表,慢指针一次 相遇则说明有环
note:注意fast是否为空,为空则不能使用fast->next
bool hasCycle(struct ListNode *head) {
if (head == NULL) return false;
struct ListNode *slow = head, *fast = head->next;
while (slow != fast && fast && fast->next ) {
slow = slow->next;
fast = fast->next->next;
}
if (fast == NULL || fast->next == NULL) return false;
return true;
}
此代码中,判断条件fast 和fast->next位置不能互换 ,否则当fast==NULL时会出错
拓展
返回链表中环的起点
示例:
n1 -> n2 -> n3 ->n4
↑ ↓
n6 <- n5
起点为n3
思路: 当快慢指针相遇时,距离环起点的节点数一定等于环外节点数,所以相遇后,在相遇点和起点建立指针,同时开始向后遍历,这两个指针的相遇点即为环起点
struct ListNode* hasCycle(struct ListNode *head) {
if (head == NULL) return false;
struct ListNode *slow = head, *fast = head->next;
while (slow != fast && fast && fast->next ) {
slow = slow->next;
fast = fast->next->next;
}
if (fast == NULL || fast->next == NULL) return NULL;
*slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
LeetCode习题汇总