LeetCode Linked List Cycle
來源:程序員人生 發布時間:2015-04-03 08:36:45 閱讀次數:2521次
1. 題目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
2.解決方案
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head){
return false;
}
ListNode* slowPoint = head;
ListNode* fastPoint = head;
while(slowPoint->next){
//slow point move one step
slowPoint = slowPoint->next;
//fast point move two step
if(fastPoint->next){
fastPoint = fastPoint->next;
}else{
return false;
}
if(fastPoint->next){
fastPoint = fastPoint->next;
}else{
return false;
}
if(slowPoint->val == fastPoint->val){
return true;
}
}
return false;
}
};
思路:用快慢指針來走,如果有環的話,1定會遇到1起。
http://www.waitingfy.com/archives/1591
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈