LeetCode -- Linked List Cycle II
1325 ワード
タイトル説明:Given a linked list,return the node where the cycle begins.If there is no cycle,return null.Note:Do not modify the linked list.Follow up:Can you solve it without using extra space?チェーンテーブルにループがあるかどうかを判断し、存在する場合はループ開始ノードに戻る.存在しない場合はNullを返します.考え方:1.スナップポインタを使用してリングの位置を見つけます.2.ループが見つかったら、スローポインタは始点に戻り、スローポインタは一歩ずつ歩き、次の出会いの位置がループの始点になります.実装コード:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode DetectCycle(ListNode head)
{
if(head == null){
return null;
}
var p = head;
var q = head;
var found = false;
while(p != null && q != null && q.next != null && !found){
var t = q;
p = p.next;
q = q.next.next;
if(ReferenceEquals(p,q)){
found = true;
}
}
if(!found){
return null;
}
// p start from head again
// and q standing where it is
// next time they meet point is where cycle starts from
p = head;
while(!ReferenceEquals(p, q)){
p = p.next;
q = q.next;
}
return q;
}
}