Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
題目意思: 給定一個鏈表, 判斷裏面是否含有環.
原題鏈接: https://leetcode.com/problems/linked-list-cycle/
這是一個典型的運用快指針和慢指針的題目.快慢指針是指移動步長不一樣,快指針每次移動的步長要大一些,慢指針每次移動的步長要小一些.
如果鏈表沒有環,則最後必然會有尾節點,就如同兩個人在操場跑步, 快指針會第一個衝過終點(NULL).
如果鏈表有環,則跑的快的人,必然會在某個時候再次遇到跑的慢的人,這個時候跑的快的人正好在環裏超過跑得慢的那個人1圈或n圈.
代碼如下:
bool hasCycle(struct ListNode *head) {
if ((NULL == head) || (NULL == head->next)) {
return false;
}
int slowStep = 1;
int fastStep = 2;
struct ListNode* slow = head;
struct ListNode* fast = head;
while (true) {
for (int j = 0; j < fastStep; ++j) {
fast = fast->next;
if (NULL == fast) {
return false;
}
if (fast == slow) {
return true;
}
}
for (int i = 0; i < slowStep; ++i) {
slow = slow->next;
}
}
}