Skip to content

Commit ec3cf3a

Browse files
committed
一快一慢两个指针,在存在环的链表里面的数学信息
1 parent 0a69fde commit ec3cf3a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

List/Linked List CycleI

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,30 @@
3333

3434
}
3535
};
36+
// 数学
37+
class Solution {
38+
public:
39+
ListNode *detectCycle(ListNode *head) {
40+
ListNode *slow = head,*fast = head;
41+
while (fast && fast->next) // 防止空指针异常
42+
{
43+
slow = slow ->next;
44+
fast = fast->next->next;
45+
if(slow == fast)
46+
break;
47+
}
48+
if(fast==nullptr || fast->next == nullptr)
49+
return NULL;
50+
else
51+
{
52+
ListNode *second = head;
53+
while (slow != second)
54+
{
55+
slow=slow->next;
56+
second=second->next;
57+
58+
}
59+
return second;
60+
}
61+
}
62+
};

0 commit comments

Comments
 (0)