試題請參見: https://oj.leetcode.com/problems/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?
解題思路
數據結構典型例題: 使用快慢指針.
快指針遍歷時, 一次遍歷2個元素; 慢指針一次遍歷1個元素.
若他倆不相等, 則不存在環.
遇到的問題
RunTime Error
遍歷時, 請檢查 fastNode->next 是否爲NULL, 否則會出現Runtime Error.
源代碼
/**
* 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* fastNode = head;
ListNode* slowNode = head;
while ( fastNode != NULL && slowNode != NULL ) {
if ( fastNode->next != NULL ) {
fastNode = fastNode->next->next;
} else {
return false;
}
slowNode = slowNode->next;
if ( fastNode == slowNode ) {
return true;
}
}
return false;
}
};