题目描述 141
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast!=NULL && fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = head
slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
题目描述 142
如果有环,如何找到入口节点 数学推导
slow走的路程 :x+y
fast走的路程:x+y+n(y+z),n表示fast指针在环内走了n圈,y+z就是环的周长
由于fast的速度是slow的两倍,因此:
2*(x+y) = x+y+n(y+z)
经过化简可以得到:x = n(y+z)-y, 即x = (n-1)(y+z) + z
其中 (n-1)(y+z)表示绕环n-1圈,
z 表示从相遇点到环入口的距离,x 表示从起点到环入口的距离;
因此当两环相遇后,把其中一个指针移到起点处,然后两个指针按照相同速度移动,再次相遇的地方就是环入口处
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
bool cycle = false;
while(fast!=NULL && fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
cycle = true;
break;
}
}
if(!cycle){
return NULL;
}
// 第一轮相遇之后,将fast重新指向链表头部
fast = head;
// 快慢指针各走一步,直到第二次相遇,此时fast位置就是相遇节点
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
fast = slow = head
cycleFlag = False
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
cycleFlag = True
break
fast = head
if cycleFlag == False:
return None
while fast != slow:
fast = fast.next
slow = slow.next
return fast