LoginSignup
1
0

More than 3 years have passed since last update.

LeetCode: 141. Linked List Cycle

Last updated at Posted at 2020-01-06

問題の要約

連結リストにサイクルがあるか判断する問題
※サイクル:連結リストのループがあり、次のリストへ辿っていくと一度通ったリストへ戻る

問題

問題へのリンク

回答1 ブルートフォース的な末尾確認

リストの次要素へ1万回遷移して末尾確認。1万回遷移後に末尾がなければ、サイクルはあるとみなすやり方で回答

bool hasCycle(ListNode *head) {
    for(int i=0;i<10000;i++){
        if(head == NULL){
            return false;
        } 
        head = head->next;
    }
    return true;
}

Runtime: 12 ms
Memory usage: 9.7 MB
提出でAcceptされたが、力任せの実装であり、サイクルがあるかどうかは具体的に判断してないので達成感なし

回答2 リストの書き換え

次に、通過した連結リストの中身は書き換えるやり方で回答。次リストへの遷移で書き換えた内容に当たったら、サイクルはあるとみなす。

class Solution {
public:
    bool hasCycle(ListNode *head) 
    {
        if(head==NULL || 
           head->val==NULL) {
            return false;
        }
        while (head->next!=NULL) {
            if(head->val==NULL) {
                return true;
            }
            head->val=NULL;
            head = head->next;
        }
        return false;
    }
}

Runtime: 12 ms
Memory Usage: 9.7 MB

提出でAcceptされた。Runtime時間は意外にも回答1と変わらなかったです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0