diff --git a/82. Remove Duplicates from Sorted List II.md b/82. Remove Duplicates from Sorted List II.md index 3248ba9..3a0b75b 100644 --- a/82. Remove Duplicates from Sorted List II.md +++ b/82. Remove Duplicates from Sorted List II.md @@ -61,11 +61,72 @@ class Solution { ``` -//時間がかかりすぎているので、ここで一旦終了。 +//ダミーの役割を理解するのに時間がかかった。一つずつの挙動の確認。 ###Step2 -・ + +83. で指摘のコメントがあったが、deleteがないため、リークに注意が必要 +LeetCodeでは解放不要ですが、deleteを意識したものへ変更。 + +```cpp +class Solution { + public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode dummy(0, head); + ListNode* node = &dummy; + ListNode* next_node = head; + + while (node && next_node) { + bool has_duplicates = next_node->next && next_node->val == next_node->next->val; + + if (has_duplicates) { + int dup_val = next_node->val; // 重複部分をすべて delete + while (next_node && next_node->val == dup_val) { + ListNode* temp = next_node; + next_node = next_node->next; + delete temp; + } + node->next = next_node; // 重複をスキップ + } + else { + node = next_node; + next_node = next_node->next; + } + } + return dummy.next; + } +}; + +``` + +他の方のGitHubを確認 +*https://github.com/maeken4/Arai60/pull/4/commits/32508ad2702b7c64d55f45023bfd816fa33358c3 + maeken さん  + 野田さんのコメント:std::unique_ptr や std::shared_ptr の使い方を確認:https://cpprefjp.github.io/reference/memory/unique_ptr.html + +* https://github.com/kazukiii/leetcode/pull/5/commits/6f0b47e756e954af07f99dad8a37c3d99c8ef65a +野田さんのコメント:early return したほうが読みやすくなると思います。 + +```cpp +if (curr->val == curr->next->val) { + curr->next = curr->next->next; + skip_count++; + continue; +} + +if (skip_count == 0) { + prev = curr; +} else { + prev->next = curr->next; +} + +skip_count = 0; +curr = curr->next; +``` ###Step3 +繰り返し 【感想】 +理解するのに時間がかかった。 +ネストが深くなると読みづらくなるので、early return をした書き方の練習。