Skip to content

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

Merged
merged 4 commits into from
Mar 18, 2024
Merged

21. Merge Two Sorted Lists #5

merged 4 commits into from
Mar 18, 2024

Conversation

colorbox
Copy link
Owner

if(list1 == nullptr)return list2;
if(list2 == nullptr)return list1;

ListNode *ret;
Copy link

Choose a reason for hiding this comment

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

ret は、変数に含まれる値がどのような役割を持つかを表していないように思います。 root または merged のほうが、より役割を表しているように思います。

Copy link
Owner Author

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){
Copy link

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){
Copy link

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();
Copy link

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);
Copy link

Choose a reason for hiding this comment

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

入力データを変更している点に違和感を感じました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

これは、引数を別変数に代入して修正するようにします。

@colorbox colorbox changed the title 21 Merge Two Sorted Lists 21. Merge Two Sorted Lists Mar 14, 2024
@colorbox colorbox merged commit 21f51a9 into main Mar 18, 2024
@colorbox colorbox deleted the 21 branch March 18, 2024 16:51
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.

2 participants