-
Notifications
You must be signed in to change notification settings - Fork 0
21. Merge Two Sorted Lists #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
if(list1 == nullptr)return list2; | ||
if(list2 == nullptr)return list1; | ||
|
||
ListNode *ret; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ret
は、変数に含まれる値がどのような役割を持つかを表していないように思います。 root
または merged
のほうが、より役割を表しているように思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
慣習的にretを使ってしまっていましたが、役割を考慮した名前付けにします。
if(list2 == nullptr)return list1; | ||
|
||
ListNode *ret; | ||
if(list1->val < list2->val){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
while ループの中の if(list1->val < list2->val){
と、処理が重複しているのが気になりました。 while ループの中の処理に統一することはできませんでしょうか?
if(list2 == nullptr)return list1; | ||
|
||
ListNode *ret; | ||
if(list1->val < list2->val){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if
と (
、)
と {
のあいだに、それぞれスペースを 1 つ空けたほうが良いと思います。
Google C++ Style Guide 等を参考にされることをお勧めいたします。
https://google.github.io/styleguide/cppguide.html#Formatting_Looping_Branching
class Solution { | ||
public: | ||
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { | ||
ListNode ret = ListNode(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ret
の代わりに、番兵を表す sentinel
を使ってはいかがでしょうか?
while(list1 != nullptr && list2 != nullptr){ | ||
// always list1 <= list2 | ||
if(list1->val > list2->val){ | ||
swap(list1, list2); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
入力データを変更している点に違和感を感じました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
これは、引数を別変数に代入して修正するようにします。
https://leetcode.com/problems/merge-two-sorted-lists/description/