Skip to content

141. linked list cycle#1

Open
ntanaka1984 wants to merge 2 commits into
mainfrom
141.-Linked-List-Cycle
Open

141. linked list cycle#1
ntanaka1984 wants to merge 2 commits into
mainfrom
141.-Linked-List-Cycle

Conversation

@ntanaka1984
Copy link
Copy Markdown
Owner

  1. linked list cycle

https://leetcode.com/problems/linked-list-cycle/description/

Step3 まで完了しました。レビューのほどよろしくお願いいたします。

class Solution {
public:
bool hasCycle(ListNode *head) {
std::set<ListNode*> visited_nodes ;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

visited_nodes; の間のスペースは消すことをお勧めいたします。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bool hasCycle(ListNode *head) {
std::set<ListNode*> visited_nodes ;

while (head != NULL) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NULL の代わりに nullptr を使用することをお勧めいたします。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘ありがとうございます。
https://cpprefjp.github.io/lang/cpp11/nullptr.html
NULL が単に整数0を表すマクロだとは知りませんでした。
以降気をつけます!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

単に while (head) でもいいでしょう。

いいと思います。

std::set<ListNode*> visited_nodes ;

while (head != NULL) {
std::set<ListNode*>::iterator is_visited_it = visited_nodes.find(head) ;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C++11 以降では contains() を使用することをお勧めいたします。

if (visited_nodes.contains(head)) {
    return true;
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘ありがとうございます。
ここではhead がvisited_nodes に含まれているか否かだけに関心があるのでcontains という名前のメソッドのほうが意図が伝わりますね。
以降はcontains を使いたいと思います。
https://cpprefjp.github.io/reference/set/set/contains.html

return true;
}
visited_nodes.insert(head) ;
head = head -> next ;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-> の両側にはスペースを空けないことをお勧めいたします。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘ありがとうございます!
そういえばメンバにアクセスする際の'.' でスペースあけるのは明らかに不自然なのですから、'->' でも空けないのが自然に感じられますね。以降気をつけます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants