File tree Expand file tree Collapse file tree 5 files changed +94
-0
lines changed Expand file tree Collapse file tree 5 files changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ 再帰によるコードを追加、同一値のグループごとに再帰させる。
3
+ 返り値を活用できていないのが気になる。
4
+ */
5
+ class Solution {
6
+ public:
7
+ ListNode* deleteDuplicates (ListNode* head) {
8
+ if (!head) return nullptr ;
9
+ while (head && head->next && head->val == head->next ->val ) {
10
+ head->next = head->next ->next ;
11
+ }
12
+ deleteDuplicates (head->next );
13
+ return head;
14
+ }
15
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ 再帰の返り値が使用されるように修正
3
+ */
4
+ class Solution {
5
+ public:
6
+ ListNode* deleteDuplicates (ListNode* head) {
7
+ if (!head) return nullptr ;
8
+ ListNode* current = head;
9
+ while (current && current->next && current->val == current->next ->val ) {
10
+ current = current->next ;
11
+ }
12
+ current = current->next ;
13
+ head->next = deleteDuplicates (current);
14
+ return head;
15
+ }
16
+ };
Original file line number Diff line number Diff line change
1
+ /* *
2
+ 4:30
3
+ Time: O(N)
4
+ Space: O(1)
5
+
6
+ リストの性質上、削除すべき要素は隣接している。
7
+ リストを頭から終わりまでチェックし、不要要素を削除していくことで実現できると判断。
8
+
9
+ */
10
+ class Solution {
11
+ public:
12
+ ListNode* deleteDuplicates (ListNode* head) {
13
+ ListNode* current = head;
14
+ while (current) {
15
+ if (!current || !current->next ) {
16
+ return head;
17
+ }
18
+ if (current->val == current->next ->val ) {
19
+ current->next = current->next ->next ;
20
+ } else {
21
+ current = current->next ;
22
+ }
23
+ }
24
+ return head;
25
+ }
26
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ 他の回答者のコードやレビューを読んで修正
3
+ whileを入れ子にするとにた処理をまとめれる
4
+ */
5
+ class Solution {
6
+ public:
7
+ ListNode* deleteDuplicates (ListNode* head) {
8
+ ListNode* current = head;
9
+
10
+ while (current) {
11
+ while (current && current->next && current->val == current->next ->val ) {
12
+ current->next = current->next ->next ;
13
+ }
14
+ current = current->next ;
15
+ }
16
+ return head;
17
+ }
18
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ 2つ目のwhileに不要な記述があったので削除
3
+ リストを先頭から見ていき、currentとその次の要素が同地な場合は削除ループを回す
4
+ 削除が完了したらcurrentを進める
5
+ 最後にheadを返して完了
6
+ */
7
+ class Solution {
8
+ public:
9
+ ListNode* deleteDuplicates (ListNode* head) {
10
+ ListNode* current = head;
11
+ while (current) {
12
+ while (current->next && current->val == current->next ->val ) {
13
+ current->next = current->next ->next ;
14
+ }
15
+ current = current->next ;
16
+ }
17
+ return head;
18
+ }
19
+ };
You can’t perform that action at this time.
0 commit comments