iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
0
自我挑戰組

刷題記錄與人生分享系列 第 23

DAY23 Linked List Cycle

題目:

https://leetcode.com/problems/linked-list-cycle/
給一個連結串列,判斷是否為循環的連結串列。

解題思路:

有2種方式可以做到,第一個是透過2個fast、slow指標,每探訪一次讓slow走一次,fast多走一次,如果是循環連結串列遲早會相遇。第二種方式是透過一個flag紀錄走到哪裡就將其flag變為true,如有循環時則判斷其flag是否為true是的話則回傳true。

C版本:

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;
}

Javascript版本:

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;
};

程式Github分享:

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.
一個人的夢想也許不值錢,但一個人的努力很值錢


上一篇
DAY22 Sum Root to Leaf Numbers
下一篇
DAY24 Intersection of Two Linked Lists
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言