https://leetcode.com/problems/linked-list-cycle/
給一個連結串列,判斷是否為循環的連結串列。
有2種方式可以做到,第一個是透過2個fast、slow指標,每探訪一次讓slow走一次,fast多走一次,如果是循環連結串列遲早會相遇。第二種方式是透過一個flag紀錄走到哪裡就將其flag變為true,如有循環時則判斷其flag是否為true是的話則回傳true。
bool hasCycle(struct ListNode *head) {
struct ListNode *fast = head;
struct ListNode *slow = head;
while(fast != NULL && fast -> next != NULL)
{
slow = slow -> next;
fast = fast -> next -> next;
if(slow == fast)
return true;
}
return false;
}
var hasCycle = function(head) {
if(head == null || head.next == null){
return false;
}
var node = head;
while(node != null ){
if(node.flag){
return true;
}
node.flag = true;
node = node.next;
}
return false;
};
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
A person's dream may not be worth the money, but one's efforts are worth the money.
一個人的夢想也許不值錢,但一個人的努力很值錢